MVC: Model
Note: This post is intended as a supplement to WTF Just Happened? A Quick Tour of Your First Rails App.
MVC: Model
Most web applications will have a database attached to them. Within an MVC architecture, we interact with data in our database through our Models using Ruby code. That's right, there is no need to learn SQL!
As a general rule, a model in a Rails application corresponds to a table in a relational database. Our model provides a way for us to treat the database table as if it were just another object in our application.
Our model class is where we can specify any business logic that relates to the object in question. We can also define an association between models.
For our Installfest application, we have the following two models:
class Post < ApplicationRecord
has_many :comments
validates_presence_of :body, :title
end
class Comment < ApplicationRecord
belongs_to :post
end
We have defined an association between the Post class and the Comments class. Specifically that a post has many comments, and a comment belongs to a post.
We have also included a business rule in the form of a validation that states that the title and the body of a post must not be empty.
Latest Articles by Our Team
Our expert team of designers and developers love what the do and enjoy sharing their knowledge with the world.
-
No app left behind: Upgrade your application to Ruby 3.0 and s...
-
A look forward from 2020
-
Testing Rails applications on real mobile devices (both design...
We Hire Only the Best
reinteractive is Australia’s largest dedicated Ruby on Rails development company. We don’t cut corners and we know what we are doing.
We are an organisation made up of amazing individuals and we take pride in our team. We are 100% remote work enabling us to choose the best talent no matter which part of the country they live in. reinteractive is dedicated to making it a great place for any developer to work.
Free Community Workshops
We created the Ruby on Rails InstallFest and Ruby on Rails Development Hub to help introduce new people to software development and to help existing developers hone their skills. These workshops provide invaluable mentorship to train developers, addressing key skills shortages in the industry. Software development is a great career choice for all ages and these events help you get started and skilled up.