Rails ActiveRecord query to match all params

五迷三道 提交于 2020-01-25 22:05:09

问题


I need to have an ActiveRecord Postgres query that returns results which match all the parameters passed in through an array.

Some background: I have a User model, which has many Topics (through Specialties). I'm passing in the Topic ids as a string (Parameters: {"topics"=>"1,8,3"}) and then turning them into an array with .split(',') so I end up with topic_params = ["1","8","3"].

Now I'm trying to return all Users who have Topics that match/include all of those. After following the answer in this question, I managed to return Users who match ANY of the Topics with this:

@users = User.includes(:topics, :organization).where(:topics => {:id => topic_params})

But I need it to return results that match ALL. I'd also be open to better ways to accomplish this sort of task overall.


回答1:


One way would be something like this

User.joins(:topics).where(topics: { id: [1, 2, 3] }).group('users.id').having('count(distinct topics.id) = 3')

Obviously I haven't your exact schema so you might have to tweak it a bit, but this is the basic setup.

Important is that the having clause counter must match the number of items you're matching with.



来源:https://stackoverflow.com/questions/41202437/rails-activerecord-query-to-match-all-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!