Forum: Ruby on Rails Addressing attribute of object specified by has_many fails

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.
Bb4bdf2b184027bc38d4fb529770cde5?d=identicon&s=25 Wes Gamble (weyus)
on 2006-05-08 23:39
I have two model objects, Document and Images.  Here are the relevant
declarations:

class Document < ActiveRecord::Base
  has_many :images

class Image < ActiveRecord::Base
  belongs_to :document

The database tables exist and foreign keys are set up correctly.

In my controller, on an initial request, calling @document.images
(nothing in it yet) is fine.

However, after I attempt to manipulate the images collection by doing:

  @document.images << images     //in this case, images is an empty
Array object

and then trying to address @document.images, I get the following error:

undefined method `images' for #<Document:0x365d6b0>

By looking at the session information, I can see that "images" is being
treated as an instance variable of the document object, and not as an
attribute - it is not listed in the attributes hash inside the document
object in the session.

Has anyone ever seen this behavior before?  It's like my document
"forgets" that it "has" images and then I can no longer count on the
ActiveRecord base methods to manipulate the images collection.

Thanks,
Wes
27f8beb57f4d56d328749b51ac886d2c?d=identicon&s=25 Kian (Guest)
on 2006-05-09 04:18
(Received via mailing list)
Wes Gamble <weyus@...> writes:

> The database tables exist and foreign keys are set up correctly.
>
> undefined method `images' for #<Document:0x365d6b0>
>
BTW, I could not repeat this error with Rails 1.1.2 in the console.
However, I think you really want to do
  <at> document.images = images   # where images == []
The << operator tries to append to argument ([]) to end of its receiver.
It
looks like AR is smart enough to avoid this (in my test) but maybe
that's
what's causing problems for you.
This topic is locked and can not be replied to.