How to set up a typical users HABTM roles relationship
Asked Answered
A

2

6

I'm quite new to this and I'm using cancan + devise for my user auth. However I'm not really sure what it means to set up a typical users HABTM roles relationship nor do I really understand what a HABTM relationship is.

Can anyone explain it really well or point me to a good tutorial or example?

Akin answered 14/7, 2011 at 6:57 Comment(0)
S
16

HABTM means has and belongs to many. You basically need a table as a middle man to track multiple id's (called a through table). When referenced as a typical users HABTM roles relationship, they really mean there would be a User model, Role model, users table, roles table, and a roles_users table. Don't forget to add the the HABTM -- roles_users -- table. A typical setup follows:

class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end

You can then use the associations like normal saying User.first.roles and Role.first.users.

There are also a couple Railscasts on your issues.

Schorl answered 14/7, 2011 at 8:2 Comment(4)
how do you create the users_roles table?Akin
rails g migration add_users_roles_tableSchorl
Sorry, hit enter too soon, edit the above with the following information: gist. Then run rake db:migrate. That should do it.Schorl
@Schorl shouldn't it be rails g migration add_roles_users_table ? I thought Rails expects the 2 models to be in alphabetical orderConstructivism
N
3

The Ruby on Rails Guides are a good starting point here also this tutorial is exactly what you want

Nambypamby answered 14/7, 2011 at 7:13 Comment(4)
I'm using the second tutorial, but it just says, 'set up a HABTM relationships' doesn't say howAkin
mikewilliamson.wordpress.com/2010/07/02/… - simple tutorial on habtmForepaw
Most of the have a UsersHaveAndBelongToManyRoles migration, how do you generate that?Akin
The docs are ridiculously vague on this...Ugh. Thanks for the tutorials.Sipple

© 2022 - 2024 — McMap. All rights reserved.