Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an 'OR' statement in ActiveRecord?

I am trying to create an 'OR' sql statement in ActiveRecord 3, I tried all kinds of variations but can't figure it out...

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, I've tried for example:

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

but it didn't work. How can I make this work?

like image 347
Thomas Traum Avatar asked Aug 27 '10 19:08

Thomas Traum


People also ask

Can you use ActiveRecord without rails?

One of the primary aspects of ActiveRecord is that there is very little to no configuration needed. It follow convention over configuration. ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is ActiveRecord naming convention?

Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns. Foreign keys - These fields should be named following the pattern singularized_table_name_id (e.g., item_id , order_id ).

What is an ActiveRecord scope?

Scopes are used to assign complex ActiveRecord queries into customized methods using Ruby on Rails. Inside your models, you can define a scope as a new method that returns a lambda function for calling queries you're probably used to using inside your controllers.


1 Answers

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))
)
like image 67
Dan McNevin Avatar answered Sep 30 '22 03:09

Dan McNevin