Forum: Ruby on Rails Access an Objects attribute as a string with HABTM

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
82d6a7ca60d1f459acf2abe5e3edd09a?d=identicon&s=25 Mernagh (Guest)
on 2008-11-14 02:29
(Received via mailing list)
I have searched many sites for the solution. And maybe there is none
or more likely it is so easy no one mentions it.

The problem is this. I have an class called Event which has a HABTM
relationship with Note.

I can do the following with no problems
 e = Event.new
 e['name'] = 'test'
 e['state'] = 'started'

But I cannot access the notes attribute in the same way
 e.notes << Note.find(:all)
 e.notes.size  #=> 11
 e['notes']  #=> nil

Why is it I can access e.name as e['name'] but not e.notes as e
['notes']?

And is there a work around to access notes only knowing the string
name ("notes")?

Will
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2008-11-14 02:31
(Received via mailing list)
On Nov 13, 9:29 pm, Mernagh <wmern...@gmail.com> wrote:
>
> But I cannot access the notes attribute in the same way
>  e.notes << Note.find(:all)
>  e.notes.size  #=> 11
>  e['notes']  #=> nil
>
> Why is it I can access e.name as e['name'] but not e.notes as e
> ['notes']?

Because name is an attribute (ie backed by some column on your table),
but notes isn't (its an association). The [] and []= methods are
equivalent to read/write_attribute, which as their names suggest are
for playing with attributes.
>
> And is there a work around to access notes only knowing the string
> name ("notes")?
>
Read up on your ruby (in particular the send method)

Fred
82d6a7ca60d1f459acf2abe5e3edd09a?d=identicon&s=25 Mernagh (Guest)
on 2008-11-14 15:25
(Received via mailing list)
Thanks Fred.
I had a look at the send method. That is exactly what I needed. Also
thanks for not giving the answer in code since I would probably not
have read up on the send method and fully understood it.

A good explanation of the send method for anyone else that wanders
here is
http://www.softiesonrails.com/2007/8/15/ruby-101-m...

and the API is defined here
http://ruby-doc.org/core/classes/Object.html#M000334


Will

On Nov 13, 8:30 pm, Frederick Cheung <frederick.che...@gmail.com>
This topic is locked and can not be replied to.