I'm using Rails 3.2 and I've got a database table in which I want to find all the rows that match the following criteria:
a = true and b = true and ( 0< c <1 or d=1), a, b, c, d are columns.
Can I have something like:
Route.where(:a => true,
:b => true,
:c => 0..1 OR :d=1
).all
Rails provides an ActiveRecord method called :includes which loads associated records in advance and limits the number of SQL queries made to the database. This technique is known as "eager loading" and in many cases will improve performance by a significant amount.
Eager loading solves this problem by creating a left outer join on the table, returning all of the data in a single query. Adding an eager load is as simple as adding an :includes statement to the controller.
Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.
I may be wrong, but I don't think you could form that query using the Arel-based where function; you'd need to form up the database query string yourself.
Assuming you're using SQLite or Postgres:
Route.where("a = true and b = true and ((c > 0 and c < 1) or d = 1)").all
I haven't tested this code, but I suspect that might do the job for you. Note this is less 'portable' code; if you change the database you're using the query may break.
In Rails 4 you can also do
Route.where(:a => true,:b => true,:c => [1,2]).all
This will find where c is 1 or 2.
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