has_many通过具有独特来源的多个模型

Dam*_*ien 7 activerecord ruby-on-rails associations

举一个每个人都熟悉的例子,想想StackOverflow.用户has_many :questions,has_many :answers和她的问题和答案,可以评论.(评论是多态的).

我希望通过对该用户的问题或答案的评论来获得针对特定用户的所有回复:

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
Run Code Online (Sandbox Code Playgroud)

当然,has_many :responses, through: [:questions, :answers], source: :comments不起作用.

是否有Rails方法可以做到这一点?

谢谢.

小智 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})'
Run Code Online (Sandbox Code Playgroud)