Has_many through several models with a unique source

For an example that everyone is familiar with, think of StackOverflow. The user has_many :questions , has_many :answers and her questions and answers can be commented on. (Commentary polymorphic).

I want to get all the answers addressed to a specific user, through comments on these questions or user responses:

 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 does not work.

Is there a way for Rails to do this?

Thanks.

+7
source share
1 answer
 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})' 
+1
source

All Articles