Rails devise simple form not saving all fields

前端 未结 2 1438
难免孤独
难免孤独 2021-02-06 18:14

When I went to generate the devise views I wanted to modify the new registration page to capture more than just the email & password. My devise user model has fields like

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-06 18:45

    Take a look at the Rails and Devise example application from the RailsApps project. I've also written a Rails Devise Tutorial that explains in detail how to add attributes to a Devise sign-up form.

    You need to tell Devise that the additional attributes are "permitted parameters." Otherwise, the "strong parameters" security measure introduced in Rails 4.0 will simply drop the unpermitted parameters, creating a new user without setting the additional attributes.

    There are three different ways to add permitted parameters in Devise:

    • override the default Devise registrations controller
    • add code to the Application controller
    • add an initializer file

    The third way is the simplest. Add a file to your application:

    # config/initializers/devise_permitted_parameters.rb
    
    module DevisePermittedParameters
      extend ActiveSupport::Concern
    
      included do
        before_filter :configure_permitted_parameters
      end
    
      protected
    
      def configure_permitted_parameters
        devise_parameter_sanitizer.for(:sign_up) << :first_name << :last_name << :phone << :addressL1 << :addressL2 << :city << :postalCode << :province
        devise_parameter_sanitizer.for(:account_update) << :first_name << :last_name << :phone << :addressL1 << :addressL2 << :city << :postalCode << :province
      end
    
    end
    
    DeviseController.send :include, DevisePermittedParameters
    

    You can see that you pass the additional parameters to the devise_parameter_sanitizer method. These two lines tell Devise to accommodate additional attributes. If you want to add other attributes, or different attributes, modify these two statements.

    The rest of the file implements a Rails concern. Concerns are modules that can be mixed into models and controllers to add shared code. Typically, these modules go in a app/controllers/concerns/ folder and are added to a controller with an include keyword. In this case, we use the Ruby send method to add our mixin to the DeviseController object, adding include DevisePermittedParameters to the DeviseController without actually editing the code.

    After making these changes and trying the application, you should see the additional attributes in the user record. If it doesn't work, show us more of your code, including the user model and controller.

提交回复
热议问题