I have a many to many relationship between two models, Order and Product. There is a joining table called Lines so that users can add quantities to the products they’d like to order.
I have products nested within orders so my routes look like the following:
resources :orders do
resources :products, :controller => "products"
end
end
I’ve able to successfully go to the index (orders/id/products) if my index.html.erb is just a placeholder, however when trying to display data I’m having issues.
My Products table that is erroring out (on the <% @products.each… line) looks like the following:
<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 looks like the following:
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 is stating my @products object is nil; however, in the console Product.all returns 4 items.
I’m a newb and this is my first time references nested resources, is it possible I’m simply trying to call it incorrectly using the instance variable @products?
Thanks
1) Do you have any products in your database? It’s good idea to check if you have any using:
@products.present?2) I suppose you want to show only products from this order. If you do, then you should write:
instead of