In Ransack, how to write a custom ransacker to search by count of associated models
Asked Answered
S

0

7

(This is a more specified version of the question that I asked previously but that has not received any answers; I hope it's not against SO’s rules)

Given that I have a Rails 4 app that has a Sponsor model and a Sponsorship model, so that a sponsor has many sponsorships, and a sponsorship belongs to a sponsor, I want to find sponsors with a number of sponsorships greater than, equal to, or less than a certain number. In order to do this, I am trying to use Ransack, a search gem that the app employs.

Here is the command that in rails console does what I need (in this particular case, returns sponsors who have more than 1 sponsorship):

Sponsor.joins(:sponsorships).group("sponsors.id").having("count(sponsorships.id) > ?",1)  

Could you please help me build a ransacker out of this command so that I could use Ransack to perform this function?

(I was told that my problem is better solved with an entirely different approach, by using count_cache in Rails, but still I would love to see this done with Ransack, if nothing else then as an instructive example.)

Septemberseptembrist answered 29/12, 2014 at 1:16 Comment(2)
So it seems doing this takes a bit of configuration and a few additional gems. All I can do is provide a blog post as I have not implemented something like this. Checkout Scopes with RansackSunfast
Wow, I thought ransackers, when tweaked appropriately, can do this on their own. The link is useful; thank you for it.Septemberseptembrist

© 2022 - 2024 — McMap. All rights reserved.