10

これらのモデルがあるとしましょう

class Message
  belongs_to :messageable, polymorphic: true
end

class Ticket
  has_many :messages, as: :messageable
  has_many :comments
end

class User
  has_many :messages, as: :messageable
  has_many :ratings
end

class Rating
  belongs_to :user
end

class Comment
  belongs_to :ticket
end

ここで、すべてのメッセージ(ticketsまたはに関連付けられているusers)をロードし、クラスのタイプに応じて、またはのいずれかで熱心にロードcommentsticketsますratingsusers

もちろんMessage.includes(:messageable).order("created_at desc")、直接関連付けられたオブジェクトのみが含まれますが、問題は、各モデルタイプから派生するさまざまな関連付けタイプをどのように含めるか(つまり、この例では、ロードを熱心に行う方法comments for ticketsratings for users)ですか?

userこれは単純な例ですが、さらに複雑なケースで、別のアソシエーションに何か他のものを含めたい場合はどうでしょうか。また、そのアソシエーションにさらに多くのインクルードが必要な場合はどうでしょうか。

4

3 に答える 3

2

これを行うために私が考えることができる唯一の方法は、各モデルの関連付けを共通の名前で複製することです。

class Ticket
  has_many :messages, as: :messageable
  has_many :comments
  has_many :messageable_includes, class_name: "Comment"
end

class User
  has_many :messages, as: :messageable
  has_many :ratings
  has_many :messageable_includes, class_name: "Rating"
end

Message.includes(:messageable => :messageable_includes) ...

この戦略を広範なソリューションとして使用するかどうかはわかりませんが、これが複雑な場合は、うまくいくかもしれません.

于 2013-02-26T19:31:09.697 に答える