Hi,
I have a “user” model, which has present “attr_accessor :password”
in the beginning, by which I wish only the password attribute could be
read and written from outside of this class. However, by retrieving a
user instance (e.g @user) by “find(:id)” from database, surprisingly I
noticed I could read every single attribute in this “user” instance
from the view, simply say: #{@user.login}, #{@user.email}, etc.
This is not what I expected, am I misunderstanding something about
the “attr” helper ?
The user model’s sexy migration:
create_table “users”, :force => true do |t|
No, you understand attr_accessor correctly. Under normal
circumstances, what you did would only expose password and no other
variables. However, there is some Rails magic going on in the
background. ActiveRecord automagically creates accessor methods for
each attribute your model has.
No, you understand attr_accessor correctly. Under normal
circumstances, what you did would only expose password and no other
variables. However, there is some Rails magic going on in the
background. ActiveRecord automagically creates accessor methods for
each attribute your model has.
Actually, you don’t normally want to use attr_accessor, or
attr_writer, or attr_reader for ActiveRecord attributes, despite the
name.
These generate methods for accessing instance variables, not database
columns. And the methods generated for AR attributes get generated
the first time the object gets a method_missing, so having an
attr_accessor with the same name as an attribute could interfere with
AR.
I think that the OP is thinking of attr_accessible which is an
ActiveRecord::Base class method to “whitelist” attributes for mass
assignment, and it’s “blacklist brother” attr_protected
Thank you Wyatt, this is so wired… I dont get why in each tutorial
book, even DHH’s, it
says: using attr_accessor to expose attribute, but actually it isn’t
like that …
I think that he meant that attr_accessor is what you’d use in a normal
Ruby (non-Rails) context to expose an attribute. That’s a fair
statement. It’s not applicable to these ActiveRecord attributes,
however, since the Rails team decided to hook method_missing in ARec
such that it issues attr_accessor calls for every content_column not
identified in the attr_protected and attr_accessible methods you’ve
mentioned.
The problem with attr_accessible and attr_protected is that they still
allow the attributes to be read, just not written. The original post
required all the attributes be hidden entirely.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.