【问题标题】:has_many :through and has_many relationship between same 2 modelshas_many :through 和 has_many 相同的 2 个模型之间的关系
【发布时间】:2013-11-25 04:03:08
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

    无论 through 模型是什么,该模型还必须有一个 has_many 关系,所以无论你有 has_many :x 和 through: :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)表进行迁移,该表将成为您的连接表,但不需要其自己的模型。但是如果你真的想保持直通关系(如果你用 join 模型做其他事情很好),那么你会这样做:

    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
    

    【讨论】:

    • 非常感谢。您的解决方案几乎是完美的,除了我必须将 belongs_to :owner, class_name: "User" 更改为 belongs_to :owner, :class_name=> "User", :foreign_key => :owner。现在一切都很好!
    • 太棒了!哦,是的,我想在 Rails 3 中你必须这样做;我主要习惯于不需要哈希火箭的 rails 4。
    猜你喜欢
    • 2019-09-26
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多