[英]rails 3 load attribute from association table
I have 3 basic models: Users, Permissions and an association model called UserPermissions so user has_many :permissions, through :user_permissions
我有3个基本模型:Users,Permissions和一个名为UserPermissions的关联模型,因此用户
has_many :permissions, through :user_permissions
My user permissions table holds the user_id, permission_id and also a privilege attribute which is a bitmask. 我的用户权限表包含user_id,permission_id以及一个特权属性,该属性是一个位掩码。 Now, when I query the user for his permissions I do something like this:
现在,当我查询用户的权限时,我将执行以下操作:
@permissions = user.permissions
and I get a nice collection of the associated permissions of that given user. 我得到了该给定用户的相关权限的很好的集合。 What I would like to do is also add the privilege field to the results so instead of this result
我还想将特权字段添加到结果中,而不是此结果
{
"id": 1,
"name": "User permissions",
"short_name": "user_permissions"
}
I need something like this: 我需要这样的东西:
{
"id": 1,
"name": "User permissions",
"short_name": "user_permissions",
"privilege": "..whatever the bitmask converts to"
}
I hope i'm making sense. 我希望我有道理。 Any ideas?
有任何想法吗?
You could just add a method to the permission class to compose your hash. 您可以只向权限类添加一个方法来组成您的哈希。 Something like
就像是
class Permission
....
def attributes_with_privilege
attributes.merge( 'privilege': user_permission.privilege )
end
...
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.