Models and Relationship

Apart from controllers and views Models are another important part an MVC framework. Model is part of the framework that communicate with database, it actually manages data and business logic of the application. Like any other MVC framework in Ruby on Rails also models are Ruby classes but they accessible across the whole application. To make application to talk with database you have to create models for example if you want to save your posts to the database you need to first create a model called Post. To access features of one model in another one you can define relationship between them, there are three types of data relationship:

1. One – to – One: a row in one table can have only one matching row in another table and vice versa.

2. One – to – Many:  this type is commonly used in which a row in first table can have many matching rows in second table but second table can have only one matching row in first table.

3. Many – to – Many: a row in one table can have many matching rows in another table and vice versa.

In Ruby on Rails creating a model is very easy just open command prompt and go to your rails application type the following command.

rails generate model Model_Name column1:type column2:type ...

generating a model also generate migration which are actually columns of the database.

in Rails to specify relationship between models has_many and belongs_to are the most common and widely used keyword, for example if we have two models named Post and Category and we want each category to have many posts then we can specify relationship between them as follows:

in Post model

class Post < ApplicationRecord
belongs_to :category

in Category model

class Category < ApplicationRecord
has_many :posts

Last week I did a lot of work, I created Categories, Users and specified relationship between users, posts and categories, for user authentication system I used a popular Ruby gem called Devise. There are several other popular gems for user authentication but Devise is a better one. A Gem is ruby plugin or library, if you have worked with JavaScript and WordPress, a Ruby Gem is similar to WP plugins and JS libraries.

Download full code from RubyonRailsCMS

Here is how our application looks like yet


Leave a Reply

Your email address will not be published.

Wordpress Social Share Plugin powered by Ultimatelysocial