How to create model in Ruby on Rails?
Last Updated :
26 Mar, 2024
In Ruby on Rails, models are like the organizers of your data. They handle interactions with your database. Think of them as the brains of your application, responsible for managing and manipulating data. They represent the structure and behavior of the information your app works with. So, whenever you need to save, retrieve, update, or delete data, models are there to help you do it smoothly and efficiently. They make it easier to work with your data in your Rails application.
For example, you might have a 'Book' model that keeps track of details like the book's title, author, and publication year. This model would have methods to retrieve a list of all books, find a specific book by its title, or update information about a book.
Before creating a model, let's create a demo project in Ruby on Rails.
Create a Demo project in Ruby on Rails
Step 1: Open the rails terminal, if you're using Windows the terminal name will be 'Ubuntu(WSL)'. Now run the following command. It will create a default project named 'myapp' in the current directory.
rails new myapp
rails new myapp
Step 2 : Use this command to get into your project directory.
cd myapp
cd myapp
Step 3 : Execute the below command in the terminal. It will create a controller file (home_controller.rb) in 'app/controllers' and corresponding view file (index.html.erb) which is our webpage in 'app/views/home'. It will also create a route in 'app/config/routes.rb' which is needed for every webpage.
rails generate controller home index
rails generate controller home index
Step 4 : Initially, when running the server, it gives the default welcome page as output. To display our home page, make changes in the 'app/config/routes.rb' file. Adding the following line in the file will set our home page as root.
root 'home#index'
set the home as root
Step 5 : Run the server using the command below and view the output at 'http://localhost:3000/'. You can also view the default web page if you don't make any change in 'routes.rb'.
rails server
rails server
Output
Open the browser and paste the link 'http://localhost:3000/'
index.html.erb output
Create model in Ruby on Rails
Now let's create a model named 'book' which will have some related attributes.
Step 1 : Execute the following command in terminal. This command creates a new model file named 'book.rb' in the 'app/models' directory and a migration file in the 'db/migrate' directory. It also sets up attributes for the Book model: title, author, and publication_year.
rails generate model Book title:string author:string publication_year:integer
-modified-660.png)
Step 2 : Now, you need to run the migration to create the corresponding table in your database. Run the following command in terminal. This will execute the migration file and create a books table in your database with columns for title, author, and publication_year.
rails db:migrate
migration
Step 3 : After creating the model and migrating the database, you can start using the Book model in your application. For example, you can create a new entry, for that open the Rails console by running the command below.
rails console
rails console
Step 4 : Now you can create rows in your table, Run the below command in rails console to create a new record in the table.
Book.create(title: "Data Structures and Algorithms Made Easy", author: "Narasimha Karumanchi", publication_year: 2016)
Create a record
Step 5 : Now, you can interact with the existing data to use in your rails application. For example, you can query the database to retrieve records, create new records, update existing ones, or delete records. The commands should be executed in rails console. The command given below retrieves all records in Book.
Book.all
Retrieve all records
Similarly, you can use following commands.
- Find books by certain conditions: Book.where(author: "Narasimha Karumanchi")
- Update a record: Book.update(title: "New Title", publication_year: 2022)
- Delete record that meet a condition: Book.where(author: "Narasimha Karumanchi").destroy_all
Conclusions:
In conclusion, models in Ruby on Rails serve as the backbone of your application, managing interactions with the database and representing data structures. They simplify data handling tasks and keep your code organized, making it easier to build robust and efficient web applications.
Similar Reads
How to create API in Ruby on Rails?
Building APIs with Ruby on Rails: A Step-by-Step GuideRuby on Rails (Rails) is a popular framework for web development, known for its convention over configuration approach. It also excels in creating robust and maintainable APIs (Application Programming Interfaces). APIs act as intermediaries, allo
3 min read
How to create table in Ruby on Rails?
In Ruby on Rails, creating tables involves using migrations, which are a powerful mechanism for managing database schema changes. Here's a detailed breakdown of the process: 1. Database Setup (Optional): While APIs can function without databases, many Rails applications use them for data persistence
3 min read
How to Create Button in Ruby on Rails?
Ruby on Rails, commonly known as Rails, is a popular web application framework written in the Ruby programming language. It follows the Model-View-Controller (MVC) architectural pattern, which separates the application's data, logic, and user interface components. Rails emphasizes convention over co
7 min read
How to Create a Linked List in Ruby?
A linked list is a form of linear data structure whereby the elements are not positioned closely together in memory. Each element here instead points to the subsequent one, thus leading to a chain-like arrangement. Creating a linked list in Ruby entails defining an information structure where each n
5 min read
How to Add Image in Ruby on Rails?
In Ruby on Rails, there are several ways to add images to your application. In this article, we will see one of the common methods which is using an assets pipeline.Steps on How to Create a ProjectStep 1: Create a demo project using the command below. It will create a project named 'myapp' in the cu
2 min read
How to Add CSS in Ruby on Rails?
This article focuses on discussing how to add Cascading Style Sheets (CSS) in Ruby on Rails. Table of Content Using SCSSUsing Plain CSSUsing Inline StylesUsing External CSS FrameworksComparison of Different ApproachesAdditional ConsiderationsConclusionUsing SCSSSCSS (Sass) is a preprocessor that ext
4 min read
How to Set Cookie in Ruby on Rails?
Cookies are small pieces of data that are sent from a website and stored on the user's computer by the user's web browser. They are commonly used for session management, user authentication, personalization, and tracking. In Ruby on Rails, you can use the 'cookies' object to set, read, and delete co
3 min read
How to Install Ruby on Rails on MacOS?
Ruby on Rails, also known as rails, is a server-side web application development framework written in the Ruby programming language. David Heinemeier Hansson developed it under the MIT License. It supports MVC (model-view-controller) architecture that provides a default structure for databases, web
2 min read
How to Upload Files in Ruby on Rails?
Uploading files in a web application is a common requirement, whether it's for user profile pictures, documents, or any other files. Ruby on Rails makes this task straightforward with its built-in tools. In this article, we'll walk through the steps to set up file uploads in a Rails app, from creati
6 min read
Ruby on Rails - How to Send Emails?
Email communication is a must-have function for those who want their web application to keep up with the current trend. The Action Mailer Framework of Ruby on Rails helps to make the tasks of sending emails easier. This article focuses on discussing sending emails using Ruby on Rails.Table of Conten
11 min read