Ruby on Rails Active Records- W3Schools

Ruby on Rails Active Record can be defined as the Object Relational Mapping (ORM) layer supplied with Rails. It follows the model of ORM only by adopting the following workflow –

* tables get mapped into classes,
* rows get mapped into objects, and
* columns get mapped into object attributes.

Rails Active Record acts as an interface between a relational database and a Ruby programme code which also binds them. You must also know that the Ruby method names are automatically generated according to the names of the fields created in the database tables.

Each of the Active Record object supports CRUD methods to access any of the database entries. Here, CRUD stands for Create, Read, Update, and Delete. These operations help in creating simple designs for your web application. It also helps in the mapping of database models into application objects.

How to Translate a Domain Model into SQL?

Translating the domain model into SQL is one of the simplest methods as it is done by writing Rails friendly SQL. But you have to follow a few rules to translate a domain model into SQL –

  • Each entity will get a table in the database which will be named after it. The entity will be represented in plural form. For example, an entity such as book will be represented as books.
  • For each entity,you will be having a unique ID named as id that will help in inserting each record in the database
  • Consider there are two entities with the name X and Y, if entity Y belongs to entity X then there has to be a table Y that would have a field under the name X_ID.
  • The values in the table represent the bulk of the fields for each entity’s properties. For example, a number with more than one digit or a string can be stored in a table.

How to Create Active Record Files (Models)?

Now, if you want to create the Active Record files for the entities of your library application (as mentioned in the previous chapter) then you are required to type in the below provided command starting with the top level of your application’s directory –

library\> rails script/generate model Book
library\> rails script/generate model Subject

The above command where you are generating a model book also helps in generating the following auto code as shown below –

In here, you will be telling the generator to create models with the name Book and Subject. These models would be storing instances of books and subjects. You can clearly see that the model names (which are Book and Subject) are starting with a capital letter and are used in their singular form. Make sure you understand that this is the Rails paradigm that you should be following each time whenever you are creating a model.

Whenever you use the generate tool, Rails always creates an actual model file with all the methods which are unique to it. This actual model file also contains all the business rules defined by you. Other than that, it also contains a unit test file so that you can perform test driven development, fixture which is a sample data file which will be used at the time of unit testing, and a Rails migration which will simplify your database tables and columns creation process to a great extent.

This will also create files with the name book.rb and subject.rb with default definitions. These files will be placed under the app/models directory of your application.

The skeleton definition under the book.rb file –

class Book < ActiveRecord::Base
end

The skeleton definition under the subject.rb file –

class Subject < ActiveRecord::Base
end

How to Create Associations between Models?
There are times when you are required to connect various models (especially when you have more than one model in your Rails application). This connection creation is done with the help of association. Rails Active Record offers three types of associations that you can perform to connect 2 or more models, which are –

  • One to one associations – As the name suggests,each item will have exactly one connection with another item. For example, a person can have exactly one PAN card and not more than that.
  • One to many associations – According to this relationship, an item can become a member of more than one object. For an instance, there are multiple books available on a single subject.
  • Many to many associations – This association takes place when the first object is linked with more than one item of the second object and the second object is also related to more than one item of the first object.

To represent these associations in your models, you need to add the following declarations while coding –

  • has_one,
  • has_many,
  • belongs_to, and
  • has_and_belongs_to_many.

It is important that you mention the type of relationship you want to establish within your library data system. Now, in order to do so, you are required to modify the book.rb and subject.rb files which will appear as the following –

class Book < ActiveRecord::Base
   belongs_to :subject
end

In the above file, you can clearly see that we have used the singular subject. This is done because one Book can belong to a single Subject only.

class Subject < ActiveRecord::Base
   has_many :books
end

On the other hand, unlike the previous file of the book.rb, we can see that in the subject.rb file we have used plural books. This is done because it is obvious that one subject can have multiple books allotted to it.

How to Implement Validations on Models?

Ruby on Rails model also offers implementation of validations. Only that data which is defined in the actual Rails model is inserted into the application’s database. And thus it is important to define only the valid data in the same location.

The validations offered by Rails model are listed below –

  • You cannot leave the value of the title field as NULL.
  • Each price field should have a numeric value.

Now, it’s time to open the book.rb file (you can locate it under the app/model path) and enter the following validations in it –

class Book < ActiveRecord::Base
   belongs_to :subject
   validates_presence_of :title
   validates_numericality_of :price, :message=>”Error Message”
end

  • validates_presence_of – This entity is inserted in the file to protect the “NOT NULL” fields if the user input is missing.
  • validates_numericality_of – This entry restricts the user from entering any kind of non-numeric data in the given fields.

Other than the above mentioned validations, there are several other common validations available in the Rails model.