0

只是想了解如何将嵌套图像重新显示在我的首页上。我对标准模型没有问题,但一直无法找到如何通过has_many嵌套属性。我所有的嵌套窗体工作正常,只是忽略了前端。Rails 4检索嵌套属性以便在index.html.erb中显示

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

有人可以分享一个例子。

欢呼

应用程序/控制器/ home_controller.rb

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

应用程序/视图/家庭/ 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> 

回答

1

你可以试试这个:

ap P /控制器/ 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 

应用程序/视图/家庭/ index.html.erb

<% @products.each do |pd| %> 
    <div><%= pd.product_name %> 
<% end %> 
<% @product_images.each do |pd| %> 
    <%= image_tag (pd.product_image(:medium)) %> 
<% end %> 
+0

甜pluk没有工作,但将其改为.MAP'高清指数 @products = Product.last(5) @product_ids = @ products.map(&:id) @product_images = ProductImage.where(:product_id => @product_ids).last(5) end' –

+0

您也可以使用'collect' – webster

+0

他们之间有很大的区别吗? –