Dan Garman
Dan Garman

Reputation: 656

Querying active record based on the value of an associations attributes

I have a Post model that has_many :feedbacks, :through => another_model. The Feedback model has a :name attribute.

I need the Posts that have feedbacks with more than 2 instances of a name.

For example:

Post One has feedbacks with names of [Like, Like, Like, Spam]

Post Two has feedbacks with names of [Dislike, Spam, Close].

I want just Post One

The best I have gotten so far is... Posts.joins(:feedbacks).where

I know I need to have a group("name") and a having count > 2 but I cannot string together all of the clauses correctly.

EDIT WITH CORRECT QUERY

Posts.joins(:another_models).group("posts.id", "another_models.feedback_id") .having("COUNT(another_models.feedback_id) >= ?", 2)

Thanks for the help.

Upvotes: 0

Views: 81

Answers (2)

Salil
Salil

Reputation: 47532

Try following

Post.joins(:feedbacks).group("posts.id").having("COUNT(DISTINCT(feedbacks.name)) < COUNT(feedbacks.id)")

Upvotes: 1

bgates
bgates

Reputation: 2373

Post.joins(:feedbacks).group("posts.id").having("COUNT(feedbacks.id) > 2")

Upvotes: 1

Related Questions