我有这样的模型:
class Person
has_many :groups
has_many :group_memberships, :foreign_key => "member_id"
end
class Group_Membership
belongs_to :member, :class_name => 'Person'
belongs_to :group
end
class Group
belongs_to :person
has_many :group_memberships
has_many :members, :class_name => "Person", :through => "group_memberships", :foreign_key => "member_id"
一个人要求一个membership
,用status false
创建一个模型。person#show
页面上group
的所有者可以看到谁要求membership
以及他参与groups
。既然groups
和group_memberships
belongs_to
person
,但group_membership
也belongs_to
group
,我如何在person#show
中查看一个视图,让person
看到谁要求memberships
groups
person
自己的,以及groups
person
有什么membership
?
编辑##
此处status
false
为默认值,因为如果所有者edit
此状态并将其设置为true
,则group
中只会接受person
。
从这个问题中获取的想法:关于轨道上的关联和模型的问题
一些伪代码,我认为它会让你走上你想要的道路:https://gist.github.com/981513
class Person
has_many :groups
has_many :group_memberships, :foreign_key => "member_id", :through => :groups
scope :owned_groups, where(:is_owner => true).joins(:group_memberships) # gets all groups where this person is owner
end
class Group_Membership
belongs_to :member, :class_name => 'Person'
belongs_to :group
# note that these attributes need to be defined
# is_owner (boolean)
# member_approved (boolean)
scope :requested, :where(:member_approved => false)
end
class Group
belongs_to :person
has_many :group_memberships
has_many :members, :class_name => "Person", :through => "group_memberships", :foreign_key => "member_id"
end
公平警告,我根本没有测试过它,我仍在学习新的AR模式:)
我认为您的group_memberships关系可能最适合作为:through关系,然后围绕该关系可能具有的不同"状态"创建范围。您也可以签出状态机以获取一些帮助。
我是这样想
的class Person
has_many :groups
has_many :group_memberships, :foreign_key => "member_id"
has_many :own_groups, :class_name => "Group", :through => "group_memberships", :foreign_key => "group_id"
end
class Group_Membership
belongs_to :member, :class_name => 'Person'
belongs_to :group
end
class Group
belongs_to :person
has_many :group_memberships
has_many :asked_group_memberships, :class_name => 'Group_Membership', :conditions => ['status = ?', false]
has_many :members, :class_name => "Person", :through => "group_memberships", :foreign_key => "member_id", :conditions => ['group_memberships.status = ?', true]
end