轨道 - 视图上的模型关联



我有这样的模型:

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。既然groupsgroup_memberships belongs_to person,但group_membershipbelongs_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

相关内容

  • 没有找到相关文章

最新更新