ActiveRecord is the model in MVC architecture. It simplifies the details of SQL by treating items within the database as objects. ActiveRecord provides the following correspondence:
You can use simple Ruby syntax to work with data.
#This code will simply creates an object of person #it will get all the atributes realted to it where #name matches Elif person = Person.where(name:"Elif").first person.age = 40 person.save # The above code could replace SQL such that # Select * From persons Where name = "Elif" # Update persons SET age = 50 Where name = "Elif"
ActiveRecord follows naming conventions to map models and database schema.
Model / Class | Table / Schema |
|
|
|
|
There are very few (or no) applications that have just one model. So, an application plausibly has a lot of models interacting with each other. A significant benefit of the ActiveRecord library is the ability to easily relate models to each other through relationships known as associations.
Consider a project xyz that has many bugs, and each of these bugs belongs to this specific project.
class Project < ApplicationRecord
has_many :bugs, dependent: :destroy
end
class Bug < ApplicationRecord
belongs_to :Project
end
With the association above, creating a bug is easy.
@bug = @project.bugs.create(published_at: Time.now)
However, without associations, the code would appear as shown below.
@bug = Bug.create(published_at: Time.now, project_id: @project.id)
Similarly, deletion is also easy with associations.
@project.destroy
This will delete the project as well as all of its bugs. Without associations, the deletion of the project as well as all of its bugs will require more lines of code.
@bugs = Bug.where(project_id: @project.id)
@bugs.each do |bug|
bug.destroy
end
@project.destroy
ActiveRecord allows an almost natural language mechanism of defining
model relationships. In our Bug model, we say that Bug objects “belong_to” Project
objects. In the Project model, we say that a Project object “has_many” associated Bug objects.
The only thing you need to set up, other than the relationship itself, is a column in
the Bugs table that enables the relationship to work. You need to store the ID of the
associated project with each Bug object, so you need to add an integer column to Bugs
called “project_id.” You can do this by creating a new migration and using a directive such
as add_column :bugs
, :project_id
, or :integer
, or by manually adding the column through another client with
SQL.
RELATED TAGS
CONTRIBUTOR
View all Courses