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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With