Model associations & view problem
|
|
Hola, I am trying to relate images to products. I am using attachment_fu, and I can upload images in the admin section without issue. So when i try and call for instance: “views/product/index” on the front end
I get the following returned:
undefined method `image' for #<Array:0x25136a8>My index method looks like this:
I have my image.rb model file set with: belongs_to :product
Not sure what I am missing. I am able to call my product categories using a similar setup without issue. Thanks in advance |
|
|
I’m not real familiar with attachment_fu, but somewhere you need this in your Product class: has_one :image This is the “other side” of the belongs_to association, so that Rails knows that a product has an image and should therefore give you a Maybe attachment_fu is supposed to do that for you automatically? If not you need to add it yourself. Let us know if that works (or not). |
|
|
Jeff, Thanks for the reply. I have tried both has_one, and has_many. No luck. Ultimately it will be a has_many relationship, but I was just trying to keep it simple – currently there is only one image in the db with that product_id. This is just strange, i know I have done this before, It is a very simple relationship. I am using restful routes and am able to pull images and display images on the ‘show’ method using:
With something like this in the view
|
|
|
Weird. Ok, try this. In Product.rb: has_many :images Now start script\console and try something like: p = Product.find(:first) p.images And you should get an array of images (assuming your product is associated to some in your development db). Does that work? (I’m assuming here that your Images table as a |
|
|
Yep that returns:
<Image id: 8, parent_id: nil, product_id: 1, content_type: "image/jpeg", filename: "GT-180_2.jpg", thumbnail: nil, size: 2084394, width: 299, height: 200, created_at: "2008-01-04 12:34:13", updated_at: "2008-01-04 12:34:13">
Which is what I want. I should note that their are actually two images. One is a thumbnail that references the image id above as parent_id. |
|
|
Its seems that everything works when I loop over it. i assume that has_many expects an array, so it fails when I just try and print it out as a method of product product.images
I think I may need to specify a default image true/false and make something like has_one :default_image, :class_name => Image, :conditions => etc...
I’ll see if that works, and allows me to limit the result. Thanks for the help |