Rails 3 - View Nested Resource Indices

I have many different relationships between two models: Order and Product. There is a Lines connection table so that users can add quantities to the products that they would like to order.

I have products embedded in orders, so my routes look like this:

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

I can successfully navigate to the index (orders / id / products) if my index.html.erb is just a placeholder, however, when I try to display the data, I have problems.

The My Products table, which is an error (in the row <% @ products.each ...), looks like this:

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

My index method is as follows:

  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 

The error indicates that my @products object is zero; however, 4 items are returned in the Product.all console.

I am new and these are my first links to nested resources, is it possible that I'm just trying to call it incorrectly using the @products instance variable?

thanks

+4
source share
1 answer

1) Do you have products in your database? It is recommended to check if you have: @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) Suppose you want to show only products from this order. If you do this then you should write:

 @products = @order.products 

instead

 @products = Product.all 
+3
source

All Articles