Подтвердить что ты не робот

Сохранение пользовательских полей при разработке Модель пользователя в рельсах 4

Я создал пользовательскую модель пользователя и добавил к ней дополнительные поля. Когда я создаю и учитываю, все работает нормально, только с помощью электронной почты, pw и pw conf.

Затем я хочу разрешить пользователю перейти на страницу редактирования и заполнить дополнительные дополнительные поля. Но, когда они подчиняются, все сохраняется как ноль.

 class RegistrationsController < Devise::RegistrationsController

   before_action :configure_permitted_parameters, if: :devise_controller?

   def configure_permitted_parameters
     devise_parameter_sanitizer.for(:sign_in){ |u| u.permit(:email, :password) }
     devise_parameter_sanitizer.for(:sign_up){ |u| u.permit(:name, :username, :about,  :email, :password, :password_confirmation)}
     devise_parameter_sanitizer.for(:account_update){ |u| u.permit(:name, :username, :about, :email, :password, :password_confirmation) }
   end

   def update
     self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
     if resource.update_with_password(user_params)
       if is_navigational_format?
         flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ? :update_needs_confirmation : :updated
         set_flash_message :notice, flash_key
       end
       sign_in resource_name, resource, :bypass => true
       respond_with resource, :location => after_update_path_for(resource)
     else
       clean_up_passwords resource
       respond_with resource
     end
   end

   def user_params 
     params.require(:user).permit(:email, :password, :current_password, :password_confirmation, :name, :username, :about) 
   end
 end

Я получаю этот вывод в консоли,

 ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"
 Processing by Devise::RegistrationsController#update as HTML
 Parameters: {"utf8"=>"✓", "authenticity_token"=>"EG8FtCTBohuG2uwUvIqmY7KTsmYY1nMAXqTfc0Li+eQ=", 
 "user"=>{"email"=>"[email protected]", "name"=>"Aaron", "username"=>"", "about"=>"", 
 "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "current_password"=>"[FILTERED]"}, "commit"=>"Update"}

User Load (2.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
Unpermitted parameters: name, username, about

Но ничего не сохраняется в базе данных, когда я проверяю консоль (с помощью User.last). Я застрял, посмотрел и понятия не имею, что не так...

4b9b3361

Ответ 1

В Rails4 у нас есть сильные параметры, поэтому

Добавьте следующую строку в свой application_controller.rb

before_filter :configure_devise_params, if: :devise_controller?
  def configure_devise_params
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(:first_name, :last_name, :gender, :email, :password, :password_confirmation)
    end
  end

Ответ 2

После работы над чем-то похожим на это, я решил использовать Application Controller, а потом обнаружил, что документация по разработке довольно проста для этого в разделе сильных параметров и дает альтернативу использованию Application Controller. https://github.com/plataformatec/devise#strong-parameters

Ниже приведен подход с Application Controller, который работал у меня.

    class ApplicationController < ActionController::Base

      before_filter :configure_permitted_parameters, if: :devise_controller?

      private

      def configure_permitted_parameters
         devise_parameter_sanitizer.for(:sign_up){ |u| u.permit(:name, :username, :about,  :email, :password, :password_confirmation)}        
         devise_parameter_sanitizer.for(:account_update){ |u| u.permit(:name, :username, :about, :email, :password, :password_confirmation) }          
      end

    end

Это должно работать одинаково, и оно напрямую перезаписывает методы в Devise::RegistrationController.

    class Users::RegistrationsController < Devise::RegistrationsController

      private

      def configure_sign_up_params
        devise_parameter_sanitizer.for(:sign_up){ |u| u.permit(:name, :username, :about,  :email, :password, :password_confirmation)}
      end

      def configure_account_update_params
        devise_parameter_sanitizer.for(:account_update){ |u| u.permit(:name, :username, :about, :email, :password, :password_confirmation) }
      end

    end

Ответ 3

Сначала создайте новое поле. для справки http://guides.rubyonrails.org/migrations.html

Вы добавили новые поля в параметр пользовательского контроллера?

   def user_params
      params.require(:user).permit(:email, :password, :password_confirmation)
    end

    def sign_up_params
      params.require(:user).permit(:email, :password, :password_confirmation)
    end

В контроллере приложений

before_filter :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :password, :password_confirmation)}

    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:email, :password, :password_confirmation)}
  end

В вашей регистрационной форме, которая переопределяет приложение, добавьте этот

class Users::RegistrationsController < Devise::RegistrationsController
     skip_before_filter :verify_authenticity_token, :only => [:ipn_notification]
  def sign_up_params
      params.require(:user).permit(:email, :password, :password_confirmation)
  end

После этого добавьте новые поля во все виды _form, покажите, отредактируйте, индексируйте.

Ответ 4

В Rails 4.2 я так и делал. У меня есть модель пользователя, на которой применяется приложение.
Используйте эту команду "rails generate devise: пользователи контроллеров" для создания пользовательских контроллеров.
Я добавил атрибут имени "имя пользователя" в мою модель пользователя

В моем контроллере

class Users::RegistrationsController < Devise::RegistrationsController
 before_filter :configure_sign_up_params, only: [:create]
 before_filter :configure_account_update_params, only: [:update]
 #rest of code as generated

   protected

    # If you have extra params to permit, append them to the sanitizer.
    def configure_sign_up_params
      devise_parameter_sanitizer.for(:sign_up) << :username
    end

   # If you have extra params to permit, append them to the sanitizer.
   def configure_account_update_params
     devise_parameter_sanitizer.for(:account_update) << :username
   end

В маршрутах

devise_for :users, controllers: {registrations: "users/registrations"}