attr_accessor和attr_accessible这是两个简单的注册申请困惑中轨
schema.rb
create_table "users", :force => true do |t|
t.string "email"
t.string "password_hash"
t.string "password_salt"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
User.rb
attr_accessible :email, :password, :password_confirmation
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
.
.
.
为什么使用密码attr_accessible和attr_accessor?
当我删除attr_accessor:密码,在轨控制台,我在执行时遇到一个错误:
user = User.new
user.password # => no method error
但是当我执行此:
user = User.new
user.email # => nil
这意味着user.email工作没有在attr_accessor中添加它,为什么?
而且这是工作:
user = User.new
user.password_confirmation # => nil
,但是当我删除:
validates_confirmation_of :password
它不会工作,为什么??。
我认为这是值得一提的是,这是为了防止同样的[质量,分配] (http://blog.mhartl.com/2008/09/21/mass-assignment-in-rails-applications/)问题,它允许[GitHub hack](http://www.extremetech.com/computing/) 120981-github-hacked-millions-of-projects-risk-being-being-modified-or-deleted)今年早些时候。 –
很好,但是你是通过大规模分配来表达的吗? –
分配,其中一个传入一组完整的属性,而不是一次一个地传递。例如,通过在上面链接的示例中使用:'@ user.update_attributes(params [:user])''。 'attr_accessible'表示“这没问题”,而没有提到'attr_accessible'的任何东西都假定需要单独显式更新。 –