PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How to print all elements that belongs_to this table

 October 21, 2022     belongs-to, has-many, ruby-on-rails     No comments   

Issue

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.


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.



Answered By - Chubas
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing