Rails Active Record is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model, which is as follows −
- Tables map to classes,
- Rows map to objects and
- Columns map to object attributes.
Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.
Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. This strategy allows simple designs and straightforward mappings between database tables and application objects.
- Each entity (such as book) gets a table in the database named after it, but in the plural (books).
- Each such entity-matching table has a field called id, which contains a unique integer for each record inserted into the table.
- Given entity x and entity y, if entity y belongs to entity x, then table y has a field called x_id.
- The bulk of the fields in any table store the values for that entity’s simple properties (anything that’s a number or a string).
Creating Active Record Files (Models)
To create the Active Record files for our entities for library application, introduced in the previous chapter, issue the following command from the top level of the application directory.
Assuming that you have created a new Rails app named Library −
malhar@ubuntu:~/library$ rails generate model Bookinvoke active_record create db/migrate/20250226073251_create_books.rb create app/models/book.rb invoke test_unit create test/models/book_test.rb create test/fixtures/books.yml
Similarly, generate Subject model −
malhar@ubuntu:~/library$ rails generate model Subjectinvoke active_record create db/migrate/20250226073318_create_subjects.rb create app/models/subject.rb invoke test_unit create test/models/subject_test.rb create test/fixtures/subjects.yml
You’re telling the generator to create models called Book and Subject to store instances of books and subjects. Notice that you are capitalizing Book and Subject and using the singular form. This is a Rails paradigm that you should follow each time you create a model.
When you use the generate tool, Rails creates the actual model file that holds all the methods unique to the model and the business rules you define, a unit test file for performing test-driven development, a sample data file (called fixtures) to use with the unit tests, and a Rails migration that makes creating database tables and columns easy.
Apart from creating many other files and directories, this will create files named book.rb and subject.rb containing a skeleton definition in the app/models directory.
Content available in book.rb −
classBook<ActiveRecord::Baseend
Content available in subject.rb
classSubject<ActiveRecord::Baseend
Creating Associations between Models
When you have more than one model in your rails application, you would need to create connection between those models. You can do this via associations.
Active Record supports three types of associations −
- one-to-one − A one-to-one relationship exists when one item has exactly one of another item. For example, a person has exactly one birthday or a dog has exactly one owner.
- one-to-many − A one-to-many relationship exists when a single object can be a member of many other objects. For instance, one subject can have many books.
- many-to-many − A many-to-many relationship exists when the first object is related to one or more of a second object, and the second object is related to one or many of the first object.
You indicate these associations by adding declarations to your models: has_one, has_many, belongs_to, and has_and_belongs_to_many.
Now, you need to tell Rails what relationships you want to establish within the library data system. To do so, modify book.rb and subject.rb to look like this −
classBook<ActiveRecord::Base belongs_to :subjectend
We have used a singular subject in the above example, because one Book can belong to a single Subject.
classSubject<ActiveRecord::Base has_many :booksend
We have used plural books here, because one subject can have multiple books.
Implementing Validations on Models
The implementation of validations is done in a Rails model. The data you are entering into the database is defined in the actual Rails model, so it only makes sense to define what valid data entails in the same location.
The validations are −
- The value of title field should not be NULL.
- The value of price field should be numeric.
Open book.rb in the app\model subdirectory and put the following validations −
classBook<ActiveRecord::Base belongs_to :subject validates_presence_of :title validates_numericality_of :price,:message=>"Error Message"end
- validates_presence_of − protects “NOT NULL” fields against missing user input.
- validates_numericality_of − prevents the user, entering non numeric data.
Besides the validations mentioned above, there are other common validations.
Built in Validation Methods
Rails provides many inbuilt validation helpers as follows:
- validates_length_of : used to check length requirements of the attribute. For example:
validates_length_of :password,:minimum=>8,:maximum=>20
- validates_inclusion_of : checks to see if an attribute is in a list of choices. For example:
validates_inclusion_of :status,:usertype=>['admin','manager','developer','tester']
- validates_associated: is used to check associations with other models. For example:
classSubject<ApplicationRecordhas_many :books validates_associated :booksend</pre>
- validates_confirmation_of : is used to validate a password or email address field with a confirmation.
validates_confirmation_of :user_name,:password
It is also possible to check multiple validations in one statement. For example,
validates :userid,:presence=>true,:length=> length:{minimum:10, maximum:50},:uniqueness=>true,:confirmation=>true
What is Next?
In the next chapter, we will learn Rails Migration, which allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code.
Leave a Reply