Addressing attribute of object specified by has_many fails

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.


Wes G. <[email protected]…> 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
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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs