Rails devise simple form not saving all fields

前端 未结 2 1440
难免孤独
难免孤独 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:46

    In Rails 4 with the introduction of Strong Parameters, parameter sanitization was moved from model to controller level. This needs to be taken care of when adding additional fields (other than email and password) to a devise model. Currently, you have not done this that is why only email and password fields are getting saved in the database and NOT the additional fields.

    You can resolve this by permitting the additional attributes of devise model via a before_action in ApplicationController.

    class ApplicationController < ActionController::Base
      #... 
      ## Add this before_action
      before_action :configure_permitted_parameters, if: :devise_controller?
    
      protected
    
      def configure_permitted_parameters
        ## To permit attributes while registration i.e. sign up (app/views/devise/registrations/new.html.erb)
        devise_parameter_sanitizer.for(:sign_up) << :attrb1 << :attrb2 
    
        ## To permit attributes while editing a registration (app/views/devise/registrations/edit.html.erb)
        devise_parameter_sanitizer.for(:account_update) << :attrb1 << :attrb2
      end
    end
    

    where,

    you need to replace :attrb1, :attrb2 with the name of attributes that you want to permit. For example :first_name, :last_name and so on.

    Refer to Devise: Strong Parameters for additional information.

提交回复
热议问题