Reputation: 1462
Say you have this:
class Question < ActiveRecord::Base
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
end
How do I search for all the questions that have answers without getting duplicate questions?
Say a question has two answers, if you do this:
Question.joins(:answers)
because it is an inner join, you'll get the question multiple times.
Is there a way to do this through the query interface without having to do a raw sql distinct or unique?
Upvotes: 4
Views: 2280
Reputation: 16345
I would just use a counter cache column. This gives you a database column in questions
which counts the number of answers attached to it. As a bonus, it's probably faster to run this query.
Here's a Railscasts video that describes how to create one: http://railscasts.com/episodes/23-counter-cache-column
Then your query becomes:
Question.where("answers_count > 0")
You could even be fancy and define this as a scope:
class Question < ActiveRecord::Base
has_many :answers
scope :answered, where("answers_count > 0")
end
It seems like a simple solution, but simple is good.
Upvotes: 4