Disjunction in ActiveRecord

拜拜、爱过 提交于 2019-12-24 00:11:48

问题


Is it possible to use ActiveRecord named_scopes to create one query with sql OR clauses?

When I use

Model.scope1.scope2

generated query is conjunction of these scopes.


回答1:


This isn't really what named scopes were designed to do, but you could probably use them with some additional code to get what you needed.

def combine_scopes(model)
  (model.scope1 + model.scope2).uniq
end

or allow any scopes to be combined

def combine_scopes(model, scope1, scope2)
  (model.send(scope1) + model.send(scope2)).uniq
end

you could even change that to allow any number of scopes using *args




回答2:


I reply as this was the first google result for "active record disjunction".

With Rails 5+ you can do something like:

Model.scope1.or(Model.scope2)

For Rails 4.2.3+ there is a backport here.

Eric-Guo created a gem where-or adding or functionality to rails >= 4.2.3 also using his gem.



来源:https://stackoverflow.com/questions/3005488/disjunction-in-activerecord

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