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'的任何東西都假定需要單獨顯式更新。 –