0

I'm having trouble showing my view correctly. I have this as my code right now:

<% for store in @stores %>
  <% store.name %>
    <% @stores.products.each do |p| %>
     <% p.name %>
    <% end %>
<% end %>

def index
 @stores = Store.paginate(:page => params[:page], :per_page => 20)
end

But end up with the error:

undefined method `products'

I'm trying to show a store and then all of its products, repeating this on the same page as much as possible e.g:

Store1
 Product1
 Product2

Store2
 Product1
 Product2
 Product3
 Product4

How can I do this?

LearningRoR
  • 26,582
  • 22
  • 85
  • 150

2 Answers2

3

Instead of <% @stores.products.each do |p| %> I think you mean <% store.products.each do |p| %>:

Also, do you not mean to have <%= on the store.name and p.name lines?

<% for store in @stores %>
  <%= store.name %>
    <% store.products.each do |p| %>
      <%= p.name %>
    <% end %>
<% end %>
Chowlett
  • 45,935
  • 20
  • 116
  • 150
2

Shouldn't that be store.products inside the loop, where you're accessing store?

<% for store in @stores %>
  <%= store.name %>
    <% store.products.each do |p| %>
     <%= p.name %>
    <% end %>
<% end %>

And = is added to the output lines. <%=

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • Then why does it give me the error: `undefined local variable or method stores` when I do this? Maybe because its in a different controller then the `StoresController`? – LearningRoR Apr 09 '12 at 20:57
  • @Railslearner If this is in a from a different controller, `@stores` has not been defined in the method you're currently calling to render this view. – Michael Berkowski Apr 09 '12 at 21:06
  • @Railslearner wait, do you mean you changed `@stores` to `stores` and now you get the error? Notice that my example above is `store.products.each`, not plural `stores.product.each`. – Michael Berkowski Apr 09 '12 at 21:07