2011-03-06 33 views
1

我的模式是这样的: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)) 

回答

0

您正在寻找的has_and_belongs_to_many关联。

+0

between User + RoleGroup和Role + RoleGroup?但连接表RoleGroups没有userid ... – Blankman 2011-03-07 02:02:06

+0

您不需要使用'has_and_belongs_to_many'为连接表建立模型。看看链接的Rails指南,它具有显示表格布局的图表。 – 2011-03-07 02:07:42

+0

嗨,你的权利是一种类型,我解决它。但是这仍然不起作用:user.RoleGroups,我会将错误放在我的问题中 – Blankman 2011-03-07 02:35:43

0

你不能这样做你想的方式。我不知道你为什么要把你的社团资本化,但也有其他一些错误。

首先,RoleGroups挂断Role(通过has_many,但更多的是在秒),这意味着你不必UserRoleGroup之间的直接连接。

其次,它似乎从更新的解释,即每个RoleGroup可以有不止一个Role,这是正常的,但在你的代码Role has_many :role_groups,这意味着每个角色都可以拥有多个角色组。这是违反直觉的命名,但也许是故意的。我将假设你的角色组包含多个角色,而不是其他角色。

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

# Models 
User 
    habtm :roles 

Role 
    habtm :users 
    belongs_to :role_group # add role.role_group_id attribute 

RoleGroup 
    has_many :roles # remove role_groups.role_id attribute 

# Console 
u = User.find(1) # get user 
r = u.roles  # get user roles 
u.roles.collect { |role| role.role_group.name } 
# ["Administrative","Editorial","User"]