views:

138

answers:

5

I'm using Rails3, ActiveRecord

Just wondering how can I chain the scopes with OR statements rather than AND.

e.g.

Person.where(:name => "John").where(:lastname => "Smith")

That normally returns name = 'John' AND lastname = 'Smith', but I'd like:

name = 'John' OR lastname = 'Smith'

A: 

If AR 3 is as good as DataMapper, you can try

Person.all(:name => "John") | Person.all(:lastname => "Smith")
Tass
Hi Tass, Isnt this querying the data table two times ? Just wanted to clarify thanks
sameera207
+1  A: 

You would do

Person.where("name = 'John' OR lastname = 'Smith'")

Right now, there isn't any other OR support by the new AR3 syntax (that is without using some 3rd party gem).

Petros
+3  A: 

Use ARel

t = Person.arel_table

results = Person.where(
  t[:name].eq("John").
  or(t[:lastname].eq("Smith"))
)
Dan McNevin
+2  A: 

You can also use MetaWhere gem to not mix up your code with SQL stuff:

Person.where((:name => "John") | (:lastname => "Smith"))
Semyon Perepelitsa
good call on this one
Nadal
+1  A: 

But if I had the where clauses as scope.

class Person < AR
  scope :firstname, lamba {|n| where(:firstname => n) }
  scope :lastname, lamba {|n| where(:lastname => n) }
end

There's no way to chain OR statements like so:

Person.firstname("John").lastname("Smith")