0

Just looking to find out how to retrieve nested images for display on my front page. I have no problems with a standard model but have been unable to find how to bring has_many nested attribute through. All my nested Forms work fine just have neglected the front end.

eg. product has nested product_images. This doesn't look like a clever way of doing it as the last five images uploaded wont necessarily be related to the last five products added.

Could someone please share an example.

cheers

app/controller/home_controller.rb

class HomeController < ApplicationController
  def index
    @products = Product.last(5)
    @product_images = ProductImage.last(5)    
  end
end

app/views/home/index.html.erb

  <% @products.each do |pd| %>
      <div><%= pd.product_name %>
       <% end %>
  <% @product_images.each do |pd| %>
        <%= image_tag (pd.product_image(:medium)) %>
  <% end %>
 </div>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

You can try this:

app/controller/home_controller.rb

 class HomeController < ApplicationController
   def index
     @products = Product.last(5)
     @product_ids = @products.collect(:id)
     @product_images = ProductImage.where(:id => @product_ids).last(5)  
   end
 end

app/views/home/index.html.erb

 <% @products.each do |pd| %>
   <div><%= pd.product_name %>
 <% end %>
 <% @product_images.each do |pd| %>
   <%= image_tag (pd.product_image(:medium)) %>
 <% end %>
webster
  • 3,902
  • 6
  • 37
  • 59