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

これを行うと、ほとんど機能します。唯一の問題は、2番目のhas_many:contentsだけが呼び出されることです。

これで、次のようなメソッドを作成して解決できます。

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

ただし、上記を行うと、コンテンツが単純な配列になるため、すべてのコンテンツスコープが失われます。

これを回避する方法はありますか?多分私は完全に間違ったアプローチを使用しています。別の方法はありますか?

ありがとう

4

2 に答える 2

0

dis_contents と fac_contents のように、コンテンツの関連付けには 2 つの異なる名前を使用します。

単一の関連付けですべてのコンテンツ オブジェクトを取得する場合は、関連付けを変更し、ポリモーフィック結合テーブルを使用する必要があります。

たぶん、この例は役立つでしょう

has_many :through + ポリモーフィックな関係

于 2012-06-07T13:28:32.017 に答える
0

dis モデルと fac モデルに大きな違いがない場合は、それらを単一のモデル セットにまとめて、これらの異なるタイプのコンテンツを区別できる「type」属性を導入できます。そうすれば、クエリを実行しようとしても問題は発生しません (より複雑なクエリを作成する場合は、問題が悪化するだけです)。さらにコンテンツ タイプを追加する場合は、スケーリングされます。

于 2012-06-07T13:25:46.980 に答える