同じモデルに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
これを行うと、ほとんど機能します。唯一の問題は、2番目のhas_many:contentsだけが呼び出されることです。
これで、次のようなメソッドを作成して解決できます。
def contents
(dises + facs).map(&:contents).flatten
end
ただし、上記を行うと、コンテンツが単純な配列になるため、すべてのコンテンツスコープが失われます。
これを回避する方法はありますか?多分私は完全に間違ったアプローチを使用しています。別の方法はありますか?
ありがとう