ruby on rails 3 - access associated record in view (show page) -


i have following association setup:

class image < activerecord::base   belongs_to :imageable, polymorphic: true    attr_accessible :photo   has_attached_file :photo, :styles => { :small_blog => "250x250#", :large_blog => "680x224#", :thumb => "95x95#" } end  class post < activerecord::base   has_many :images, as: :imageable    accepts_nested_attributes_for :images   attr_accessible :comments, :title, :images_attributes end 

to access image post within index page, example, put code in block , loop through using each:

<% @posts.each |p| %>    <% p.images.each |i| %>     <%= image_tag(i.photo.url(:large_blog), :class => 'image') %>   <% end %> <% end %> 

so when comes accessing post in show view accessing 1 record thought access image so:

<%= image_tag(@post.image.photo.url(:large_blog), :class => 'image') %> 

but seems if can't error like: undefined method 'image'.

im not thinking basic here , hoping point me in right direction.

you have got has_many relation image in post model, can't access post.image you've got collection of images each post. in plain english:

you've got here:

a collection of post (@posts) iterate each method

<% @posts.each |p| %> 

now p means single post has collection of images

  <% p.images.each |i| %> 

and again, iterate on images , display every single image attached post

    <%= image_tag(i.photo.url(:large_blog), :class => 'image') %>   <% end %> <% end %> 

so can see every post may have several images , if have 1 image still array, can access @post.images.each or @post.images.first (or last) if want first one.

if want able @post.image should add post model:

class post < activerecord::base has_one :image, conditions: { primary: true} # if want specify main photo , of course if have  'primary' in image model (...) 

you can add additional conditions (as in code above) select newest photo, etc. can read more here


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -