ruby-on-rails – 多对多用户和组,但组拥有所有者
发布时间:2020-12-16 23:34:36 所属栏目:百科 来源:网络整理
导读:我无法理解/包围我的大脑.我正在尝试创建一个允许这样的关系: 用户可以属于多个组 组可以有很多用户 一个组拥有一个用户的所有者 集团所有权可以转让 我已经设置了多对多关系,但我似乎无法理解如何设置所有权功能. 这是我目前在我的模型中所拥有的: class
我无法理解/包围我的大脑.我正在尝试创建一个允许这样的关系:
>用户可以属于多个组 我已经设置了多对多关系,但我似乎无法理解如何设置所有权功能. 这是我目前在我的模型中所拥有的: class Group < ActiveRecord::Base has_and_belongs_to_many :users attr_accessible :name,:description,:isPublic,:tag_list,:owner end class User < ActiveRecord::Base has_and_belongs_to_many :groups attr_accessible :name,:owner_id end 任何帮助将不胜感激!! 解决方法
您可以通过以下几种方式进行设置:
1)使用连接模型并在连接模型上放置一个标志,指定组成员是所有者. class Group < ActiveRecord::Base has_many :memberships has_many :users,through: :memberships attr_accessible :name,:owner end class Membership < ActiveRecord::Base belongs_to :group belongs_to :user #this table has a flag called owner and thus a method called owner? end class User < ActiveRecord::Base has_many :memberships has_many :groups,:owner_id end 2)保留现有的HABTM并添加另一个连接模型以跟踪所有权. class Group < ActiveRecord::Base has_and_belongs_to_many :users has_many :group_ownerships has_many :owners,through: :group_owernships,class_name: "User" attr_accessible :name,:owner end class GroupOwnership < ActiveRecord::Base belongs_to :group belongs_to :user end class User < ActiveRecord::Base has_and_belongs_to_many :groups has_many :group_ownerships has_many :owned_groups,class_name: "Group" attr_accessible :name,:owner_id end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |