Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Join in rails model

    • 0
    • 3
    • 1
    • 2
    • 0
    • 0
    • 0
    • 0
    • 390
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: