You need to use ARel, scopes are always connected with AND
.
ActiveRecord OR for existing scopes
-
29-05-2022 - |
Question
I have an existing model with a set of complex scopes:
scope :test1 , where(gift: true)
scope :test2 , lambda {|time| where("last_created_at > ?", time)}
scope :test3 , where(approved: true)
I can than do something like
User.test1.test2.test3.all
Now, say I want to append a global OR scope to this. i.e. select all this (test1 + test2 +test) OR when user is an admin (not working code, of course):
scope :admin , where("OR admin=", true)
Is there any way to do this with existing scope, or does this require an all new rewrite with AREL or plain SQL?
One hack I found for this is :
scope :admin , where("1=1) OR admin=1 AND (1=1", true)
But, I mean, can this get any uglier than that.. :)
Solution
OTHER TIPS
As a weird hack, the scope I suggest above does work. However , as a plain solution, it seems that easiest approach is to perform two separated queries and concat the active record results. I used the concat option, I think it also makes the code readable, with probably negligible, if any, impact to performances.
scope :test1 , where(gift: true)
scope :test2 , lambda {|time| where("last_created_at > ?", time)}
scope :test3 , where(approved: true)
scope :admin , where(admin: true)
data1 = User.test1.test2.test3.all
data2 = User.admin.all
(data1 + data2)