2010-11-23 65 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