has_many通过帮助,我做错了什么?

时间:2011-03-06 21:22:55

标签: ruby-on-rails

我的模特是这样的:

User
   has_and_belongs_to_many :Roles

Role
   has_and_belongs_to_many :Users

表:

roles_users
   user_id
   role_id

roleGroups
   id
   role_id
   some_column

现在我想在User模型上创建另一个关联,它将是用户所属的所有roleGroup的集合。

即。如果用户处于id为1和2的角色中,则获取role_id = 1和2的所有RoleGroup。

我认为我需要使用通过,因为它基于用户的角色关联权利吗?

我试过了:

User
   has_many  :RoleGroups, :through => :Roles

Role
   has_many :RoleGroups, :through => :User

但是我收到一个错误说:

ActiveRecord::HasManyThroughSourceAssociationMacroError: Invalid source reflection macro :has_many :through for has_many :RoleGroups, :through => :Roles.  Use :source to specify the source reflection.

更新的 好吧,我的模特现在看起来像这样:

User
   habtm :Roles
   has_many :RoleGroups, :through => :Roles

Role
  habtm :Users
  has_many :RoleGroups

RoleGroup
  belongs_to :Role

mysql表:

roles_users
   user_id
   role_id

role_groups
   id
   role_id
   col3
   col4
   ..

如果我这样做:

u = User.find(1)
u.Roles  (works fine)
u.RoleGroups   #see error

错误讯息:

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'roles.user_id' in 'where clause': SELECT `role_groups`.* FROM `role_groups` INNER JOIN `roles` ON `role_groups`.role_id = `roles`.id WHERE ((`roles`.user_id = 1))

2 个答案:

答案 0 :(得分:0)

您正在寻找has_and_belongs_to_many协会。

答案 1 :(得分:0)

你不能按照你的想法去做。我不确定你为什么要把你的协会资本化,但也有其他一些错误。

首先,RoleGroups挂起Role(通过has_many,但在一秒内更多),这意味着{{1}之间没有直接连接}和User

其次,从您的更新说明中可以看出,每个RoleGroup可以有多个RoleGroup,这是正常的,但在您的代码Role中,这意味着每个角色都可以拥有更多而不是一个角色组。这是违反直觉的命名,但也许是故意的。我将假设您的角色组包含多个角色,而不是相反。

第三,您不能将HABTM用作Role has_many :role_groups模型。 HABTM只使用数据库中的表,而不是Rails模型,因此:through表中的信息不能直接使用; roles_users需要实际的has_many :foos :through => :bars模型。

Bar