2011-12-14 5 views
7

誰もがよく知っている例を取るために、StackOverflowを考えてみましょう。 ユーザーhas_many :questionshas_many :answersと彼女の質問と回答がコメントされる場合があります。 (コメントは多態性です)。has_manyユニークなソースを持つ複数のモデルを介して

は、私はすべての応答がこのユーザーの質問も回答のいずれかにコメントを経由して特定のユーザ宛取得したい:

もちろん
class User < ActiveRecord::Base 
    has_many :questions 
    has_many :answers 
    has_many :comments 
    has_many :responses, through: [:questions, :answers], source: :comments 
end 

class Question < ActiveRecord::Base 
    belongs_to :user 
    has_many :answers 
    has_many :comments, as: :commentable 
end 

class Answer < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :question 
    has_many :comments, as: :commentable 
end 

class Comment < ActiveRecord::Base 
    belongs_to :commentable, polymorphic: true 
end 

has_many :responses, through: [:questions, :answers], source: :commentsは動作しません。

これを行う方法はありますか?

ありがとうございました。

+0

私は、これはここで回答されていると思います。おかげでhttp://stackoverflow.com/questions/3487730/reverse-polymorphic-associations – DGM

+0

@DGM悲しいことではありません。ところで、受け入れられた答えは本当にIMOを行う正しいことではありません。 – Damien

+0

アサーションでのSQLの書き込み条件はどうですか? – blade

答えて

1
has_many :responses, :class_name => "Comment", :finder_sql => 
      'SELECT DISTINCT comments.* ' + 
      'FROM comments c, questions q, answers a ' + 
      'WHERE (c.commentable_id = a.id and c.commentable_type='Answer' and a.user_id = #{id}) or (c.commentable_id = q.id and c.commentable_type='Question' and q.user_id = #{id})' 
関連する問題