2010-11-23 66 views
4

我在兩個模型Order和Product之間有多對多的關係。有一個名爲Lines的連接表,用戶可以將數量添加到他們想要訂購的產品中。Rails 3 - 嵌套資源的索引視圖

我有嵌套訂單中的產品,讓我的路線如下所示:

resources :orders do 
    resources :products, :controller => "products"  
    end 
end 

我已經能夠成功地轉到指數(訂單/ ID /產品),如果我的index.html.erb是隻是一個佔位符,但是當試圖顯示數據時我遇到了問題。

我的產品表示數是從(上<%@ products.each ...行)看起來如下:

<table> 
    <tr> 
    <th>URL</th> 
    <th></th> 
    <th></th> 
    <th></th> 
    </tr> 

<% @products.each do |product| %> 
    <tr> 
    <td><%= product.url %></td> 
    <td><%= link_to 'Show', product %></td> 
    <td><%= link_to 'Edit', edit_order_products_path(product) %></td> 
    <td><%= link_to 'Destroy', order, :confirm => 'Are you sure?', :method => :delete %></td> 
    </tr> 
<% end %> 

我的索引方法如下所示:

def index 
    @order = Order.find(params[:order_id]) 
    @products = Product.all  


    respond_to do |format| 
     format.html # index.html.erb 
     format.xml { render :xml => @products } 
    end 
    end 

錯誤是陳述我的@products對象是零;但是,在控制檯中Product.all會返回4個項目。

我是一個新手,這是我第一次引用嵌套資源,是否有可能我只是試圖使用實例變量@products錯誤地調用它?

謝謝

回答

3

1)您的數據庫中是否有產品?這是很好的主意,檢查,如果您有任何使用:@products.present?

<% if @products.present? %> 
    <% @products.each do |product| %> 
    <tr> 
    <td><%= product.url %></td> 
    <td><%= link_to 'Show', product %></td> 
    <td><%= link_to 'Edit', edit_order_products_path(product) %></td> 
    <td><%= link_to 'Destroy', order, :confirm => 'Are you sure?', :method => :delete %></td> 
    </tr> 
<% end %> 
<% else %> 
<tr> 
    <td colspan=4>You don't have any products yet.</td> 
</tr> 
<% end %> 

2)我想你只想顯示產品的順序。如果你這樣做,那麼你應該寫:

@products = @order.products 

,而不是

@products = Product.all