mea*_*rly 6 many-to-many ruby-on-rails
我无法理解/包围我的大脑.我正在尝试创建一个允许这样的关系:
我已经设置了多对多关系,但我似乎无法理解如何设置所有权功能.
这是我目前在我的模型中所拥有的:
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, :description, :owner_id
end
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激!!
Sea*_*ill 11
您可以通过以下几种方式进行设置:
1)使用连接模型并在连接模型上放置一个标志,指定组成员是所有者.
class Group < ActiveRecord::Base
has_many :memberships
has_many :users, through: :memberships
attr_accessible :name, :description, :isPublic, :tag_list, :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, through: :memberships
attr_accessible :name, :description, :owner_id
end
Run Code Online (Sandbox Code Playgroud)
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, :description, :isPublic, :tag_list, :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, through: :group_owernships, class_name: "Group"
attr_accessible :name, :description, :owner_id
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3940 次 |
| 最近记录: |