如何设置典型的用户HABTM角色关系 [英] How to set up a typical users HABTM roles relationship

查看:155
本文介绍了如何设置典型的用户HABTM角色关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的,我正在使用cancan + devise为我的用户auth。然而,我并不确定建立典型用户HABTM角色关系的意义,也不知道HABTM关系是什么。



任何人都可以解释或者指向一个好的教程或例子?

解决方案

HABTM意味着拥有并属于许多。您基本上需要一张桌子作为中间人来跟踪多个id(称为直通表)。当被引用为典型用户HABTM角色关系时,他们确实意味着将有一个用户模型,角色模型,用户表,角色表和一个roles_users表。不要忘了添加HABTM - roles_users - 表。一个典型的设置如下:

  class User< ActiveRecord :: Base 
has_and_belongs_to_many:roles
end

class Role< ActiveRecord :: Base
has_and_belongs_to_many:users
end

然后可以使用协会正常说 User.first.roles Role.first.users



还有一个 couple Railscasts


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?

解决方案

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.

这篇关于如何设置典型的用户HABTM角色关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆