Rails: How to retrieve an attribute from a related model? -


i seem stuck problem should more obvious me: how can attributes related model show in view.

in application there these 2 models:

products
product_images

i'm writing while i'm on go , don't have exact code available. created necessary associations, product has_many product_images , product_image belongs_to product. image model has url, default (boolean) flag , of course product_id.

in product index view i'd display default image product. sake of simplicity though let's assume i'm fine showing first picture - conditions should easy introduce once works.

so in products index view there's (again, memory):

@products.each |p|     <h3><%= p.name %></h3>     <%= image_tag p.product_images.first.url %>     <p><%= p.description %></p> end 

while description , name of product alone display fine include image_tag view breaks nomethoderror stating url undefined method in class nil. keep simpler got rid of image_tag , wanted see url printed in paragraph - problem remains of course. if try p.product_images.first view prints assume sort of id object/model fine, tells me association ok. why rails think url attribute should method?

i checked rails console see if correct syntax retrieve related attribute. (again, memory - syntax errors possible):

p = product.first => [successful - shows first product] p.product_images.first => [successful - shows first image model] p.product_images.first.url => [successful - shows me single attribute, url image] 

as can tell i'm new , appreciated. of course read rails documentation, active record query guide focuses on getting data current model , wasn't able find i'm missing in sample app.

why work in console not in view?

it because 1 of product not have productimage.

you can correct adding method in productshelper so:

def product_image(product)     return if product.product_images.blank?      image_url = product.product_images.first.url     return if image_url.nil?      image_tag(image_url).html_safe end 

and call view so:

@products.each |p|     <h3><%= p.name %></h3>     <%= product_image(p) %>     <p><%= p.description %></p> end 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -