| Start |
| .where 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 following model: To find all people with the first name of Sven: To find all people with the first name of Sven and last name of Schrodinger: In the above example, the sql output shows that records will only be returned if both the first_name and the last_name match. query with OR condition To find records with first_name == 'Bruce' OR last_name == 'Wayne' |
| .where with an array 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: If the array contains a nil, the SQL will be modified to check if the column is null: |
| Scopes 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: Scopes can be called directly off the model class: Scopes can be chained: The where method and other query type methods can also be chained: Behind the scenes, scopes are simply syntactic sugar for a standard class method. For example, these methods are functionally identical: Default Scope in your model to set a default scope for all operations on the model. There is one notable difference between the scope method and a class method: scope-defined scopes will always return an ActiveRecord::Relation, even if the logic within returns nil. Class methods, however, have no such safety net and can break chainability if they return something else. |
| Get first and last record 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: It will generate following sql query: And will return following record: To get the last record from users table we need to type following command: It will generate following sql query: And will return following record: Passing an integer to first and last method creates a LIMIT query and returns array of objects. It will generate following sql query. And It will generate following sql query. |
| where.not where clauses can be negated using the where.not syntax: Supported by ActiveRecord 4.0 and later. |
| Ordering You can order ActiveRecord query results by using .order: If not specified, ordering will be performed in ascending order. You can specify it by doing: .order also accepts a string, so you could also do As the string is raw SQL, you can also specify a table and not only an attribute. Assuming you want to order users according to their role name, you can do this: The order scope can also accept an Arel node: |
| Includes 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. Author.joins(:books).where(books: { bestseller: true } ) will load only authors with conditions into memory without loading books. Use joins when additional information about nested associations isn't required. |
| .find_by 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: Mind that find_by doesn't throw any exception by default. If the result is an empty set, it returns nil instead of find. If the exception is needed may use find_by! that raises an ActiveRecord::RecordNotFound error like find. |
| .delete_all 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 don't get triggered). |
| ActiveRecord case insensitive search 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 to do this in a safe way: Arel will apply the appropriate LIKE or ILIKE construct for the database engine configured. |
| .group and .count We have a Product model and we want to group them by their category. This will query the database as follows: Make sure that the grouped field is also selected. Grouping is especially useful for counting the occurrence - in this case - of categories. As the query shows, it will use the database for counting, which is much more efficient, than retrieving all record first and do the counting in the code: |
| .distinct (or .uniq) If you want to remove duplicates from a result, you can use .distinct(): This queries the database as follows: .uniq() has the same effect. With Rails 5.0 it got deprecated and it will be removed from Rails with version 5.1. The reason is, that the word unique doesn't have the same meaning as distinct and it can be misleading. Furthermore distinct is closer to the SQL syntax. |
| Joins joins() allows you to join tables to your current model. For ex. will produce the following SQL query: Having table joined, you will have access to it: Pay attention on plural form. If your relation is :has_many, then the joins() argument should be pluralized. Otherwise, use singular. Nested joins: which will produce: |
| Limit and Offset 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 It will generate following sql query. As offset is not mentioned in above query so it will return first three records. It will generate following sql query. |
| ActiveRecord Bang (!) methods 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 ActiveRecord code this way to save you time and trouble. The ActiveRecord methods which accept a bang (!) are: .create! .take! .first! .last! .find_by! .find_or_create_by! #save! #update! - all AR dynamic finders
|