How to select columns from multiple table in rails?

7k views Asked by At

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.

3

There are 3 answers

1
MrYoshiji On

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

0
FonchoRG On

The statement Order.joins(:user).select('orders.*, users.name') get the orders with all its columns and the name of the user in the same record, the table names should be passed as plural in the select instruction.

0
Adamu Dankore Muhammad On

You do not need to make any special selection in your controller.

In your controller:

@orders =  Order.last(5) # gets 5 most recent orders

In your view:

@orders.each do |order|
  order.user.name # or order.user.first_name, e.t.c
end

Just access the user from the order.