Rails 3,如何确保Group has_one user.role = groupleader
我当前的组模型:
class Group < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :users, :through => :memberships
end
我当前的用户模型
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
#some more stuff
end
成员资格模型
class Membership < ActiveRecord::Base
attr_accessible :user_id, :group_id
belongs_to :user
belongs_to :group
end
角色模型
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
我安装了一个能力类和 CanCan 来处理角色。我有一个角色类型 groupleader,需要确保一个组只有一个 groupleader...
我认为它类似于: Group has_one User.role :groupleader... 但我知道不是这样。
My current Group model:
class Group < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :users, :through => :memberships
end
My Current User Model
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
#some more stuff
end
Membership Model
class Membership < ActiveRecord::Base
attr_accessible :user_id, :group_id
belongs_to :user
belongs_to :group
end
Role Model
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
I have a Ability class and CanCan installed to handle roles. I have a role type groupleader and need to make sure a Group has only one groupleader...
I think its something like: Group has_one User.role :groupleader... but I know thats not it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望用户表确定用户可以在组的上下文中执行哪些操作,那么将角色放在用户表中对我来说是没有意义的。
有意义的地方是将其放在组和用户的
memberships
表中。该表中的记录将具有三列:user_id
、group_id
和role
。然后,要检索该组的领导者,您可以执行如下查询:
其中
group
是一个Group
对象,即Group.first
或 <代码>Group.find(13)。如果需要的话,这就留下了一种可能性,即你可以在一个团队中拥有多个领导者。
如果您的角色位于单独的表中,那么您可以执行以下操作:
It doesn't make sense to me to have the role on the users table if you want it to determine what the user can do within the context of a group.
Where it would make sense is to have it on the
memberships
table for groups and users. Records in this table would then have three columns:user_id
,group_id
androle
.Then to retrieve the leader for the group you would execute a query like this:
Where
group
is aGroup
object, i.e.Group.first
orGroup.find(13)
.This then leaves open the possibility that you can have more than one leader for a group further down the track if required.
If your roles are in a separate table, then you can do this: