Rails 4 检索嵌套属性以在 index.html.erb 中显示

Rails 4 retrieve nested attributes for display in an index.html.erb

只是想了解如何检索嵌套图像以显示在我的首页上。我对标准模型没有任何问题,但无法找到如何使 has_many 嵌套属性通过。我所有的嵌套表单都可以正常工作,只是忽略了前端。

例如。产品已嵌套 product_images。这看起来不是一个聪明的做法,因为最后上传的五张图片不一定与最后添加的五个产品相关。

有人可以分享一个例子吗。

干杯

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>

你可以试试这个:

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 %>