我想在同一个模型上创建 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
但是,如果我执行上述操作,我会丢失所有内容范围,因为内容会变成一个简单的数组。
有没有办法解决?也许我使用了完全错误的方法。还有其他方法吗?
谢谢