Reputation: 574
I am following Michael Hartls rails tutorial . Here is the User model class .
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation, :nick_name
has_many :microposts, dependent: :destroy
has_secure_password
end
The User table in database doesnt contain password/password_confirmation fields. It only has a
password_digestfield. I'm confused , Shouldn't I be using an attr_accessor method on fields that are not present in a table ? I thought that the code must look something like this :
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation, :nick_name
attr_accessor :password, :password_confirmation
has_many :microposts, dependent: :destroy
has_secure_password
end
Because password/password_confirmation are not present in table column , Is'nt attr_accessor required ? I'm thoroughly confused .
Upvotes: 0
Views: 756
Reputation: 399
No need to be confused. You are right, attr_accessor
is required for non-db backed fields, as it's the getter/setter for that field. On the other hand, attr_accessible
is used by Rails to identify which properties are allowed to be assigned by a request (aka. a white list). Given your example, if you don't include password
and password_confirmation
in the attr_accessible
attributes, you wouldn't be able to mass assign them in a request.
Upvotes: 1
Reputation: 4737
Read the source and it will make sense why the User
class does not call attr_accessor :password
. The macro itself calls attr_reader :password
and you have no need for a password_confirmation
accessor.
You also need to think of what the User
class should actually be concerned with. password
and password_confirmation
has to do with authentication. Even though has_secure_password
ends up defining authentication related methods in the User
class, I argue that we should not be concerned with the implementation details of authentication specifically in the User
class. Instead ActiveModel::SecurePassword is. Hence you should not be concerned with defining methods for password
and password_confirmation
unless specific features that you yourself are defining need to access these attributes.
It's just unfortunate that attr_accessible
is required to allow mass assignment of these values in the controller. But there's a reason why this is deprecated in Rails 4.
Upvotes: 1