views:

37

answers:

1

Ok, I'm not sure that my title was clear enough, but I will try to explain

I have two tables: orders that has_many items and items that belongs_to orders. I just started to learn RoR and stuck with a simple task. All I want is to display orders and related items like this:

Order 1:
Item 1
Item 2

Order 2:
Item 1
Item 2
...

I know how to display orders or items separately, I know how to display items' orders (item.order.id), but how to display orders and items in the table like above? In template where I display orders I could go through each item every iteration and compare it foreign order_id with order.id, but that would be awkward. I'm supposing that I should get items into some kind of multidimensional hash where key would be order_id and then I could just refer to this hash by order id and get all items in it, but I'm not sure it's correct.

God, hope what I have written here is understandable ;)

+2  A: 

When you define a has_many relation, you automatically get the methods to query those objects. In this case, the method order.items.

So you can do:

Order.find_each do |order|
  puts "Order #{order.id}:"
  order.items.each do |item|
    puts "Item #{item.id}"
  end
end

(I used find_each method, which is available from Rails 2.3+. You could use a simple Order.all.each though.

Chubas
Excellent, thanks! But if I want to use it in a template, it won't work, right? It says undefined method 'items'.
Arty
It should work, assuming you are correctly calling on an object of type `Order`. How exactly are you calling it in your view?
Chubas
<% Order.all.each do |order| %>
Arty
Ok, I got it. It works. Should have been 'item' not 'items'. Thanks a lot!
Arty