views:

56

answers:

2

This is an embarrassing noob question, but...

How do you do an OR query in Rails 3 ActiveRecord. All the examples I find just have AND queries.

Edit: without using a SQL string!

+1  A: 

Just add an OR in the conditions

Model.find(:all, :conditions => ["column = ? OR other_column = ?",value, other_value])
Toby Hede
This is more the syntax for Rails 2, and it requires me to write at least portion of a sql string.
pho3nixf1re
+1  A: 

Use ARel

t = Post.arel_table

results = Post.where(
  t[:author].eq("Someone").
  or(t[:title].matches("%something%"))
)

The resulting SQL:

ree-1.8.7-2010.02 > puts Post.where(t[:author].eq("Someone").or(t[:title].matches("%something%"))).to_sql
SELECT     "posts".* FROM       "posts"  WHERE     (("posts"."author" = 'Someone' OR "posts"."title" LIKE '%something%'))
Dan McNevin
Feels a little messy, but at least I'm not writing sql, which just feels wrong! I'm going to have to look into using Arel more.
pho3nixf1re
The great thing is that you don't have to do it all at once, you can build up queries and it won't actually hit the database until you actually need the data. This example was just combined for brevity.
Dan McNevin