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)