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

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Wes G. (Guest)
on 2006-05-09 01:39
I have two model objects, Document and Images.  Here are the relevant

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.

Kian (Guest)
on 2006-05-09 06:18
(Received via mailing list)
Wes G. <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.
looks like AR is smart enough to avoid this (in my test) but maybe
what's causing problems for you.
This topic is locked and can not be replied to.