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.
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})'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With