1

我想在同一个模型上创建 2 个 has_many 但它通过不同的模型(这是一个连接表)

这是代码:

class Content
  belongs_to :dis
  belongs_to :fac

  has_many :dis_representations, :through => :dis
  has_many :fac_representations, :through => :fac
end

class Fac
  has_many :fac_representations
  has_many :contents
end

class Dis
  has_many :dis_representations
  has_many :contents
end

class DisRepresentation
  belongs_to :user, :foreign_key => "e_user_id"
  belongs_to :dis
end

class FacRepresentation
  belongs_to :user, :foreign_key => "e_user_id"
  belongs_to :fac
end

class User
  has_many :dis_representations, :foreign_key => "e_user_id"
  has_many :fac_representations, :foreign_key => "e_user_id"
  has_many :dises, :through => :dis_representations
  has_many :facs, :through => :fac_representations
  has_many :contents, :through => :dises, :source => :contents
  has_many :contents, :through => :facs :source => :contents
end

现在我想这样做:

User.first.contents

如果我这样做,它几乎可以工作。唯一的问题是只有第二个 has_many :contents 被调用。

现在我可以通过创建这样的方法来解决它:

def contents
    (dises + facs).map(&:contents).flatten
end

但是,如果我执行上述操作,我会丢失所有内容范围,因为内容会变成一个简单的数组。

有没有办法解决?也许我使用了完全错误的方法。还有其他方法吗?

谢谢

4

2 回答 2

0

如果 dis 和 fac 模型没有显着不同,那么您可以将它们折叠成一组模型并引入一个“type”属性,让您可以区分这些不同类型的内容。然后你在尝试查询它时不会有问题(它只会在你想编写更复杂的查询时变得更糟),并且当你想添加更多内容类型时它会扩展。

于 2012-06-07T13:25:46.980 回答
0

我会为内容关联使用两个不同的名称,例如 dis_contents 和 fac_contents。

如果您想通过单个关联检索所有 Content 对象,您应该更改您的关联并使用多态连接表。

也许这个例子会有所帮助

has_many:通过+多态关系

于 2012-06-07T13:28:32.017 回答