In rails if we want to establish inner join relationship between two models we can do it using joins method of activerecord.
For example, consider the following Company, Product, Review and Vote models:
class Company < ActiveRecord::Base
  has_many :products
end
class Product < ActiveRecord::Base
  belongs_to :company
  has_many :reviews
end
class Review < ActiveRecord::Base
  belongs_to :product
  has_many :votes
end
class Vote < ActiveRecord::Base
  belongs_to :review
end
Single level association: Company.joins(:products)
Corresponding sql query is:
SELECT companies.* FROM companies
  INNER JOIN products ON products.company_id = companies.id
Single level nested association:  Company.joins(:products => :reviews)
Corresponding sql query is:
SELECT companies.* FROM companies
  INNER JOIN products ON products.company_id = companies.id
  INNER JOIN reviews ON reviews.product_id = products.id
Multiple level nested association: Company.joins(:products => [{:reviews => :votes}])
Corresponding sql query is:
SELECT companies.* FROM companies
  INNER JOIN products ON products.company_id = companies.id
  INNER JOIN reviews ON reviews.product_id = products.id
  INNER JOIN votes ON votes.reviews_id = reviews.id
                       
                    
0 Comment(s)