Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.
Source: https://guides.rubyonrails.org/active_record_basics.html
By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class Book
, you should have a database table called books.
To create Active Record models, subclass the ApplicationRecord
class and you're good to go:
class Product < ApplicationRecord
end
This will create a Product
model, mapped to a products
table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model.
When creating a new Model that depends on a previously created Model (like comments on articles), we make use of an Active Record Association.
First, take a look at app/models/comment.rb
:
class Comment < ApplicationRecord
belongs_to :article
end
This is very similar to the Article
model that you saw earlier. The difference is the line belongs_to :article
, which sets up an Active Record association. You'll learn a little about associations in the next section of this guide.
Source: https://guides.rubyonrails.org/getting_started.html#adding-a-second-model-generating-a-model
More info: https://guides.rubyonrails.org/association_basics.html