2015-12-02 77 views
0

我有一個包含產品和類別的Ruby應用程序。Ruby數組僅存儲最後一個值,不是所有值

我想要一個類別索引頁面,顯示每個類別的1張產品照片。

現在,它顯示最後所有類別的產品圖片。 (所以,有16個大類,它顯示的產品照片上的每個類別16類)

我想我需要修復我如何存儲或致電產品陣列。我怎麼做?

碼 -

在categories_controller.rb

def index 
    @categories = Category.all.order('name ASC') 
    @products = [] 

    @categories.each do |category| 
    @products = Product.where(category_id: category.id).take(1) 
    end 
end 
在類別

/index.html.erb

<% @categories.each do |category| %> 
    <% @products.each do |product| %> 
     <%= link_to image_tag(product.image), category %> 
    <% end %> 
    <%= link_to category.name, category %> 
    <%= category.description %> 

回答

0

在你index行動,更改行:

@products = Product.where(category_id: category.id).take(1) 

要:

@products << Product.where(category_id: category.id).take(1) 

UPDATE:

由於take(1)將數組返回一個對象,你需要簡單地將其更改爲:

@products << Product.where(category_id: category.id).take 
+0

謝謝!我在控制器文件中將=更改爲<<。加載類別索引頁時,現在我得到未定義的方法'圖像'錯誤。我應該對索引代碼進行進一步更改嗎? – supertext

+0

你的'Product'模型中有'image'字段嗎?請解釋與'image'相關的數據結構。 – Yang

+0

是的,產品型號包含圖像。該圖像顯示正確,當它被調用數組中的最後一項。但是,只要我更改爲<<,那麼圖像在索引文件中成爲該調用的錯誤。產品數據庫中沒有空圖像值或任何其他空值。 – supertext

相關問題