问题
Environment: Rails 4, Devise 3.2.2
Given I added two fields (name, profession) to my devise model.
When I sign up
Then I see in the database the new columns not affected.
Below are my controller and model classes
#custom controller
class UsersController < Devise::RegistrationsController
before_action :configure_permitted_parameters
#devise's controller extensions
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:name, :email, :profession, :password, :password_confirmation)
end
end
end
#Devise Model
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessor :name, :profession
validates :name, presence: true
validates_uniqueness_of :email, :name
end
I specify that devise runs correctly and uses my custom controller.
I also checked in the params hash and it includes the new field values as you can see:
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"F3AjMd1/EpYvuhckEMPUkiMZ1szHa6ba7OMbjjSltOk=", "user"=>{"name"=>"test", "email"=>"you@contect.com", "profession"=>"prof", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Save"}
And below is the generated sql:
INSERT INTO "users" ("created_at", "email", "encrypted_password", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Tue, 11 Feb 2014 15:14:56 UTC +00:00], ["email", "you@contect.com"], ["encrypted_password", "$2a$10$Bn3LIldBUDPHKO0vrXd7peVz6q/42hOrCOcqdbvBMHVeEtn4EfKma"], ["updated_at", Tue, 11 Feb 2014 15:14:56 UTC +00:00]]
which contains none of new fields added.
Any hint will be welcome, I've been stuck for more than one hour.
回答1:
Remove this line from your model:
attr_accessor :name, :profession
This is overriding the accessors already provided by activer record after you migrated your model and added those fields. This is causing them not to be saved to the db.
来源:https://stackoverflow.com/questions/21732803/devise-custom-fields-not-saved-after-signing-up