开发者

Why would one use both attr_accessor and attr_accessible on the same field?

开发者 https://www.devze.com 2023-02-21 22:08 出处:网络
attr_accessor :password attr_accessible :name, :passw开发者_StackOverflow中文版ord, :password_confirmation
attr_accessor :password  
attr_accessible :name, :passw开发者_StackOverflow中文版ord, :password_confirmation  


attr_accessor defines a property and is part of Ruby. Se more here.

attr_accessible makes a property available for mass-assignment and is part of Rails. Se more here


I assume you are using an authentication library in your Rails project. Password is probably a "virtual attribute" in your Rails model (as in, there's no password column in your database table). You need the password accessor methods to keep the plain text password in an instance variable, and then there's probably a callback method that encrypts/hashes that password when your model is saved in the database probably in a different column.


Say that, for example, your DB has a table called posts. posts has the following fields: name, encrypted_password. And you have to following Rails model:

class Post < ActiveRecord::Base
  attr_accessor :password
  attr_accessible :name, :password, :password_confirmation
end

Without the attr_accessible it would be possible to set encrypted_password through mass assignment. Basically with attr_accessible you specify which attributes may be set through mass assignment (in this case leaving encrypted_password out of the loop.

attr_accessor creates accessors on your class for the name/symbol given. Basically what it does for you is:

def password= param
  @password = param
end

def password
  @password
end

I'm guessing that in your case the attr password is used in a before_save/create callback. Doing something with password and sets the encrypted_password. But I'm only guessing here.

Hope that helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号