Search code examples
ruby-on-railsactive-record-query

Active record query using joins


I have three different models User, Order, Product:-

class User < ActiveRecord::Base
  has_many :orders
  has_many :products
end
class Product < ActiveRecord::Base
      has_many :orders
end
class Order < ActiveRecord::Base
  belongs_to :user
  belongs_to :product 
end

How to find all the products which an user has ordered using a one line active-record query?


Solution

  • This is explained in the ActiveRecord documentation:

    Product.joins(:orders).where(orders: { user_id: user.id })