我的模式是这样的:has_many通过帮助,我做错了什么?
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
现在我想创建的用户模型相互关联起来,这将是所有roleGroups的集合用户所属。
也就是说,如果用户在角色与ID的1和2,然后取其中ROLE_ID = 1和2
我想我需要通过使用,因为它是基于用户角色的所有RoleGroups协会权利?
我想:
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))
between User + RoleGroup和Role + RoleGroup?但连接表RoleGroups没有userid ... – Blankman 2011-03-07 02:02:06
您不需要使用'has_and_belongs_to_many'为连接表建立模型。看看链接的Rails指南,它具有显示表格布局的图表。 – 2011-03-07 02:07:42
嗨,你的权利是一种类型,我解决它。但是这仍然不起作用:user.RoleGroups,我会将错误放在我的问题中 – Blankman 2011-03-07 02:35:43