Class and Database
Your model classes' database tables should be called in the plural form and in lowercase. For example, if the name of a model class is Student, the table name will be Students. Rails will find the relevant table to your model class without any configuration code if you follow this standard. It even recognizes plural nouns as plurals of singular nouns, such as 'people' as the plural of 'person.'
Rails has a feature that allows you to add plurals to a model. Using Inflector, add code to config/environment.rb to specify your own pluralization.
In case you don't want to name your database in the plural form, you may configure Rails to use singular-named database tables by adding the following line to
config/environment.rb file:
ActiveRecord::Base.pluralize_table_names = false
Translating a Domain Model into SQL
It's often straightforward to convert a domain model to SQL, as long as you remember to write Rails-friendly SQL. In practice, you must adhere to certain guidelines.
- Each entity (such as a book) is given its own database table, but in the plural (books).
- A field named id exists in each entity-matching table, and it holds a unique integer for each entry placed into the table.
- If entity y belongs to entity x and table y contains a field called x_id, then table y will have a field called x_id.
- The values for that entity's simple properties (anything that's a number or a text) are stored in the majority of fields in any table.
Creating Active Record Files (Models)
Use the following command from the top level of the application directory to generate the Active Record files for our entities for library application:
library\> rails script/generate model Book
library\> rails script/generate model Subject
The auto code generated by above rails generate model book commands is as follows:
invoke active_record
create db/migrate/20115501100134_create_books.rb
create app/models/book.rb
invoke test_unit
create test/models/book_test.rb
create test/fixtures/books.yml
You're instructing the generator to construct models for books and subjects called Book and Subject. You'll see that you've capitalized Book and Subject, and singular form is used. This is a Rails paradigm that you should adhere to when creating a model.
While using the generate tool, Rails creates the actual model file, which contains all of the model's unique methods and the business rules you define, as well as a unit test file for test-driven development, a sample data file (called fixtures) to use with the unit tests, and a Rails migration, which makes creating database tables and columns simple.
Apart from many other files and directories, this will produce files named book.rb and subject.rb in the app/models directory, each with a skeleton definition.
Content available in the book.rb:
class Book < ActiveRecord::Base
end
Content available in subject.rb:
class Subject < ActiveRecord::Base
end
How to Create Associations between Models
You must connect your models in your Rails application if you have more than one. This can be accomplished through associations. There are three types of associations supported by Active Record:
- one-to-one: When one object has exactly one of another, it is said to be a one-to-one relationship. A human, for instance, has exactly one birthday, and a dog has precisely one owner.
- one-to-many: When a single object can be a member of many other objects, this is known as a one-to-many relationship. One subject, for example, may have a large number of books.
- many-to-many: When the first object is related to one or more of the second object, and the second object is related to one or many of the first object, a many-to-many relationship exists.
These connections are indicated by declaring has one, has many, belongs to, and has and belongs to many in your models.
Now you must tell Rails what kinds of associations you wish to create in the library data system. To accomplish so, make the following changes to book.rb and subject.rb:
class Book < ActiveRecord::Base
belongs_to :subject
end
We selected a single subject in the preceding example because a single Book might belong to a single subject.
class Subject < ActiveRecord::Base
has_many :books
end
We've used plural books because one subject can have numerous books here.
Implementing Validations on Models
The validations are implemented using a Rails model. Because the data you're entering into the database is described in the Rails model, it's only natural to specify what constitutes valid data in the same place.
The validations are as follows:
- The value of the title field should not be NULL.
- The value of the price field should be numeric.
Open book.rb in the app\model subdirectory and put the following validations:
class Book < ActiveRecord::Base
belongs_to :subject
validates_presence_of :title
validates_numericality_of :price, :message=>"Error Message"
end
-
validates_presence_of: "NOT NULL" fields are protected from missing user input.
-
validates_numericality_of: This validation stops the user from inputting non-numerical data.
FAQs
-
What does ActiveRecord do in Rails?
Active Records in Rails provide a connection and interface between relational database tables and Ruby computer code that manipulates database records. The names of Ruby methods are derived automatically from the field names of database tables.
-
Is ActiveRecord an ORM?
Object Relational Mapping (ORM) is a database management technique that involves "mapping" database tables to classes and instances of classes to rows in the tables. ORMs such as Active Record are just one example; others include Sequel. DataMapper.
-
What is the active record pattern in Rails?
The active record pattern is a method of retrieving information from a database. A class encapsulates a database table or view. As a result, each object instance is associated with a single table row. When an item is created, a new row is added to the table when it is saved.
Key Takeaways
In this blog, we learned about Active Records in Rails, its basics, how to create one, translation of Domain Model into SQL, and Association between Models.
To learn more, please head to Coding Ninjas Blogs, where we bring to you exciting technical blogs.
Happy Learning!