Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select columns from multiple table in rails?

I have two tables User and Order and association between those two table as follow.

in User model

  has_many :orders, dependent: :destroy

in Order model

  belongs_to :user

I want to select all data from order table but instead of user_id I want to select name of that user from User table.

how can I do in rails? thanks in advance.

like image 618
sank Avatar asked Oct 18 '25 18:10

sank


1 Answers

You can simply do the following:

orders = Order.where(your_conditions).includes(:user)

And then:

orders.each do |order|
  order.user.name # implies that every order has a user
  # or
  order.user&.name # won't fail if order.user returns nil
end

This is called eager loading, you can find documentation here: http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

like image 183
MrYoshiji Avatar answered Oct 20 '25 08:10

MrYoshiji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!