vendredi 1 juin 2018

Select model based on amount of related models with certain conditions

I have a Post that has_many :comments. Let's say Comment has the following field: another_model_id. I would like to select Posts, that have from 2 to 5 comments with another_model_id = 10 (for example). I tried several constructions but with no success :(

Example of what I tried:

# Invalid SQL syntax error
Post
  .joins(:comments)
  .select("count(comment.another_model_id = 10) as comments_count)
  .where("comments_count BETWEEN 2 AND 5")

I have literally no idea where to dig. Is it possible to achieve that in a single query? Thanks!

Aucun commentaire:

Enregistrer un commentaire