我可以添加基于另一个关联的关联吗? [英] Could I add an association based on another association?
本文介绍了我可以添加基于另一个关联的关联吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的用户模型如下所示:
My User model looks like:
User
habtm :Roles
Role
habtm :Users
RoleExtension
belongs_to :Role
mysql 表:
users
id
..
roles
id
..
roles_users
user_id
role_id
role_extensions
id
role_id
feature_id
..
..
现在一切似乎都运行良好.
Now everything seems to be working fine so far.
现在我希望 User 模型拥有一个基于 habtm Roles 集合的 RoleExtensions 集合.
示例:
user = User.find(1)
user.Roles (returns roles with id's of 1,2,3)
所以我想要:
user.RoleExtensions
返回所有在(1,2,3)中有role_id的角色扩展
to return all Role extensions that have role_id in (1,2,3)
推荐答案
通常您会使用 has_many, :through
关联,但这不适用于 has_and_belongs_to_many
关系.
Normally you'd use a has_many, :through
association, but that doesn't apply to has_and_belongs_to_many
relations.
因此,在您的 User 模型中:
So, instead, in your User model:
def role_extensions
return roles.inject([]) do |array, role|
role.role_extensions do |re|
array.include?(re) ? array << re : array
end
end
end
然后 my_user.role_extensions
应该返回属于所有用户角色的所有角色扩展的数组.
Then my_user.role_extensions
should return an array of all role extensions belonging to all the user's roles.
注意:我没有测试过这个,但它应该可以工作
更新:我更喜欢这个
def role_extensions
return roles.inject([]) { |array, role| array << role.role_extensions }.flatten!.uniq
end
这篇关于我可以添加基于另一个关联的关联吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文