Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_many through multiple models with a unique source

To take an example everyone is familiar with, think of StackOverflow. A user has_many :questions, has_many :answers and her questions and answers may be commented. (Comment is polymorphic).

I want to get all the responses addressed to a particular user via a comment on either this user's questions or 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

Of course, has_many :responses, through: [:questions, :answers], source: :comments doesn't work.

Is there a Rails way to do it?

Thanks.

like image 964
Damien Avatar asked Dec 14 '11 17:12

Damien


1 Answers

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})'
like image 144
Ankun Avatar answered Oct 12 '22 23:10

Ankun