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

时间:2011-12-14 17:59:28

标签: ruby-on-rails activerecord associations

举一个每个人都熟悉的例子,想想StackOverflow。 用户has_many :questionshas_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

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

是否有Rails方法可以做到?

感谢。

1 个答案:

答案 0 :(得分: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})'