I\'m trying to access all comments from a given user with user.comments
. The query is to go through two different models, which likely both return results. My r
Since we couldn't use has_many, through
here because comments
come from both of organisers
and participants
. I just think there are 2 solutions here:
Solution #1 Define comments
method:
class User < ActiveRecord::Base
def comments
Comment.joins([{organiser: :user}, {participant: :user}])
.where(users: {id: self.id})
end
end
So then your query to find comments is:
User.first.comments
Solution #2 Use scope in Comment
class Comment < ActiveRecord::Base
scope :from_user, -> (user) {
joins([{organiser: :user}, {participant: :user}]).where(users: {id: user.id})
}
end
So your query will be like:
user = User.first
comments = Comment.from_user(user)