Search code examples
ruby-on-railsrubyruby-on-rails-3.2rails-activerecordarel

ActiveRecord OR for existing scopes


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

  • You need to use ARel, scopes are always connected with AND.