Question

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.

I hope what I have written here is understandable.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top