Tutorial by Examples

The where method is available on any ActiveRecord model and allows querying the database for a set of records matching the given criteria. The where method accepts a hash where the keys correspond to the column names on the table that the model represents. As a simple example, we will use the foll...
The where method on any ActiveRecord model can be used to generate SQL of the form WHERE column_name IN (a, b, c, ...). This is achieved by passing an array as argument. As a simple example, we will use the following model: class Person < ActiveRecord::Base #attribute :first_name, :string ...
Scopes act as predefined filters on ActiveRecord models. A scope is defined using the scope class method. As a simple example, we will use the following model: class Person < ActiveRecord::Base #attribute :first_name, :string #attribute :last_name, :string #attribute :age, :integer ...
where clauses can be negated using the where.not syntax: class Person < ApplicationRecord #attribute :first_name, :string end people = Person.where.not(first_name: ['Mark', 'Mary']) # => SELECT "people".* FROM "people" WHERE "people"."first_name&quot...
You can order ActiveRecord query results by using .order: User.order(:created_at) #=> => [#<User id: 2, created_at: "2015-08-12 21:36:23">, #<User id: 11, created_at: "2015-08-15 10:21:48">] If not specified, ordering will be performed in ascending order. Y...
If you need an ActiveRecord method to raise an exception instead of a false value in case of failure, you can add ! to them. This is very important. As some exceptions/failures are hard to catch if you don't use ! on them. I recommended doing this in your development cycle to write all your ActiveRe...
You can find records by any field in your table using find_by. So, if you have a User model with a first_name attribute you can do: User.find_by(first_name: "John") #=> #<User id: 2005, first_name: "John", last_name: "Smith"> Mind that find_by doesn't thr...
If you need to delete a lot of records quickly, ActiveRecord gives .delete_all method. to be called directly on a model, to delete all records in that table, or a collection. Beware though, as .delete_all does not instantiate any object hence does not provide any callback (before_* and after_destroy...
If you need to search an ActiveRecord model for similar values, you might be tempted to use LIKE or ILIKE but this isn't portable between database engines. Similarly, resorting to always downcasing or upcasing can create performance issues. You can use ActiveRecord's underlying Arel matches method...
Rails have very easy way to get first and last record from database. To get the first record from users table we need to type following command: User.first It will generate following sql query: SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1 And will return following recor...
We have a Product model and we want to group them by their category. Product.select(:category).group(:category) This will query the database as follows: SELECT "product"."category" FROM "product" GROUP BY "product"."category" Make sure that t...
If you want to remove duplicates from a result, you can use .distinct(): Customers.select(:country).distinct This queries the database as follows: SELECT DISTINCT "customers"."country" FROM "customers" .uniq() has the same effect. With Rails 5.0 it got deprecate...
joins() allows you to join tables to your current model. For ex. User.joins(:posts) will produce the following SQL query: "SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"" Hav...
ActiveRecord with includes ensures that all of the specified associations are loaded using the minimum possible number of queries. So when querying a table for data with an associated table, both tables are loaded into memory. @authors = Author.includes(:books).where(books: { bestseller: true } ) ...
You can use limit to tell the number of records to be fetched, and use offset to tell the number of records to skip before starting to return the records. For Example User.limit(3) #returns first three records It will generate following sql query. "SELECT `users`.* FROM `users` LIMIT 3&q...

Page 1 of 1