attr_accessor

42 views
Skip to first unread message

Pat

unread,
Nov 6, 2007, 2:04:34 AM11/6/07
to Ruby on Rails: Talk
Folks, newbie here and I have a quick question about attr_accessor.

I'm developing a very basic CMS and I set up a simple class for a
user. In that class I use attr_accessor to set up the read, write,
etc methods.

Then in a very basic a controller I create an instance variable @post
= post(:all) and I then render the title of the post along with the
user name in the view. Strangely, the title appears, but the user
name doesn't. BUT, if I remove the attr_accessor in the model the
user name appears just fine. I thought that attr_accessor didn't do
that and that methods like attr_accessible or attr_protected should be
used instead to restrict access to the method.

What's happening here? Do miss understand how attr_accessor works?


TIA!

Frederick Cheung

unread,
Nov 6, 2007, 3:55:16 AM11/6/07
to rubyonra...@googlegroups.com

On 6 Nov 2007, at 07:04, Pat wrote:
>
>
> What's happening here? Do miss understand how attr_accessor works?

I suspect the attr_accessor is overwriting the accessor methods that
rails creates for your database attributes.
attr_protected etc... are only for dealing with mass assignment (ie
Post.new(params[:post])))

Fred

Bob Showalter

unread,
Nov 6, 2007, 11:59:45 AM11/6/07
to rubyonra...@googlegroups.com

attr_accessor is a Ruby (not Rails) thing that sets up "getter/setter"
methods for an instance variable. You shouldn't use attr_accessor for
the columns in an AR model; AR creates getter/setter methods for you.

What are you trying to accomplish with attr_accessor here?

Reply all
Reply to author
Forward
0 new messages