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?
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.
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.
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 ).
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.
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))
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With