Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Choosing Between has_many :through and has_and_belongs_to_many

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 686
    Comment on it

    In Rails we can establish many to many relationship between two models in two ways 1) by using has_and_belongs_to_many 2) by using has_many :through associations.

    We generally use HABTM when we dont require a third intervening model to join two other models i.e the third table in the database will have just the foreign keys of the other two tables. The third model will have no extra attributes or any validation and callbacks.

    Example:

    class User < ActiveRecord::Base
     has_and_belongs_to_many :roles
    end
    
    class Role < ActiveRecord::Base
    has_and_belongs_to_many :users
    end
    

    Here we have to create a third joining table users_roles.

    In case of has_many :through relation we can have many to many relation in indirect way through a third joining model.

    Example: Below are the three models of an online shopping website:

    class User< ActiveRecord::Base
      has_many :user_items
      has_many :items, through: :user_items
    end
    
    class UserItem< ActiveRecord::Base
      belongs_to :user
      belongs_to :item
    end
    
    class Item < ActiveRecord::Base
      has_many :user_items
      has_many :users, through: :user_items
    end
    

    Here the user_items table will have the foreign keys of the two table and some additional information like date_of_delivery, payment_method(cash or card) e.t.c.

 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: