Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord Query: select record where has at least one in a has many relationship

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?

like image 935
earnold Avatar asked Oct 31 '25 05:10

earnold


1 Answers

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.

like image 141
Jeremy Roman Avatar answered Nov 02 '25 08:11

Jeremy Roman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!