How to set up a typical users HABTM roles relationship

烈酒焚心 提交于 2019-12-18 13:33:22

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/6689540/how-to-set-up-a-typical-users-habtm-roles-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!