views:

29

answers:

2

Hey,

I am trying to create an 'OR' sql statement in ActiveRecord 3, I tried all kinds of variations but cant figure it out... I am new to it so I might be missing something obvious.

For example I want this query to include multiple 'channel_ids' and have it return all posts for any of the channel IDs. This works for one:

Post.where(:user => 'mike').where(:channel_id => 0).limit(20)

but I cant figure out how to do it with multiples, tried for example:

Post.where(:user => 'mike').where(:channel_id => ?,[0,1,2,3]).limit(20)

but no luck... Many thanks for any help!

+1  A: 

Try this:

Post.where("posts.user = ? OR posts.channel_id IN (?)", "mike", ids)
KandadaBoggu
You should let ActiveRecord escape lists for you instead of doing it yourself. You can leave `ids` in there as-is, no `join` required and it will be expanded to a comma-separated list for you automatically.
tadman
@tadman, thx, updated the answer.
KandadaBoggu
A: 

Use the Arel methods to do this:

t = Post.arel_table
ids = [1,2,3]

Post.where(
  t[:user].eq("mike").or(t[:channel_id].in(ids))
)
Dan McNevin
works perfect, many thanks. Heard of Arel before and will read up on it now. So neat.
Thomas Traum