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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 83
    Comment on it

    has_and_belongs_to_many association is used in rails where we dont need a third joining model to establish the relation between the two model. There will be no additional columns (except the foreign keys) of the third joining table.

    For example I have two models User and role. User model has all user of a college . So the roles of a user can be student,student coordinator,professor,Head of department, Principal, e.t.c. or one user can have more than one role like a student can also be student coordinator and a professor can also be a HOD of department .All these roles will be in role table. So to maintain this relation we can use HABTM.

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

    Now here the joining table will be users_roles and we have to write a migration for generating this table. This joining table will have two foreign keys, user_id and role_id.

    How to fetch the roles of a user.

    @user = User.find(params[:id])

    @roles = @user.roles

 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: