has_many:通过和has_many相同的2个模型之间的关系

时间:2013-11-25 04:03:09

标签: ruby-on-rails ruby-on-rails-3 rails-activerecord

列表中有一个所有者(用户)。列表中还有许多小组成员(也是用户)。我尝试定义三个模型之间的关系:User,List和Panelist。但我无处可去。

user.rb

class User < ActiveRecord::Base
  has_many :lists
  has_many :panelMemberships, :through => :panelists, :source => :lists
end

list.rb

class List < ActiveRecord::Base
  belongs_to :user
  has_many :panelMembers, :through => :panelists, :source => :user
end

panelist.rb

class Panelist < ActiveRecord::Base
  belongs_to :list
  belongs_to :user
end

我尝试了所有不同的组合,但似乎没有任何效果。提前感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:1)

模型也必须具有has_many关系,无论通过模型是什么,所以无论你在哪里has_many:x,通过:: y,你还需要说has_many:y。如果小组成员是用户,您也不应该将小组成员模型与您的用户模型分开(除非您正在进行STI,否则您不是)。根据我的理解,你正试图做这样的事情:

class User < ActiveRecord::Base
  has_many :owned_lists, class_name: "List", foreign_key: :owner_id  # this is for the owner/list relationship
  has_and_belongs_to_many :lists  # for the normal panelist / list relationship
end

class List < ActiveRecord::Base
  belongs_to :owner, class_name: "User"
  has_and_belongs_to_many :users
end

然后,您需要为users_lists(具有用户ID和列表ID)表进行迁移,该表将是您的连接表,但不需要自己的模型。但是,如果你真的想要保持完整的关系(如果你用连接模型做其他的事情,这很好),那你就做了:

class User < ActiveRecord::Base
  has_many :owned_lists, class_name: "List", foreign_key: :owner_id  # this is for the owner/list relationship
  has_many :panel_memberships
  has_many :lists, through: :panel_memberships 
end

class List < ActiveRecord::Base
  belongs_to :owner, class_name: "User"
  has_many :panel_memberships
  has_many :users, through: :panel_memberships
end

class PanelMembership < ActiveRecord::Base
  belongs_to :user
  belongs_to :list