Ruby on Rails, often called Rails, is a popular open-source web application framework written in Ruby. It follows the Model-View-Controller (MVC) architectural pattern and provides a set of conventions for rapid development. In this tutorial, we’ll cover the basics of Ruby on Rails and guide you through creating a simple web application.
Prerequisites
- Basic understanding of Ruby programming language
- Ruby installed on your machine
- Rails installed (installation instructions available on the Rails website)
Step 1: Create a New Rails Application
Open your terminal and run the following command to create a new Rails application:
rails new myapp
This will create a new directory called myapp
with a basic Rails application structure.
Step 2: Navigate to Your Rails Application
Navigate to the newly created application directory:
cd myapp
Step 3: Generate a Scaffold
Let’s generate a simple scaffold for managing a list of items. In this example, we’ll create a Task
model with a title and description.
3.1 Generate Scaffold
Run the following command to generate the scaffold:
rails generate scaffold Task title:string description:text
3.2 Run Database Migrations
After generating the scaffold, run the database migrations to create the necessary tables in the database:
rails db:migrate
Step 4: Start the Rails Server
You can now start the Rails server to see your application in action:
rails server
Visit http://localhost:3000/tasks
in your web browser, and you should see the generated scaffold for managing tasks.
Step 5: Customize Views (Optional)
5.1 Update the Task Form
Navigate to app/views/tasks/_form.html.erb
and customize the form fields if needed.
5.2 Customize the Task Index Page
Navigate to app/views/tasks/index.html.erb
to customize the task listing page.
5.3 Add Additional Features
You can add features like authentication, validations, and more based on your application requirements.
Step 6: Create a Controller (Optional)
If you want to add more functionality, you can create a custom controller and routes.
6.1 Generate a Controller
rails generate controller Welcome index
This command generates a Welcome
controller with an index
action.
6.2 Update Routes
In config/routes.rb
, you can define routes to map URLs to controller actions:
Rails.application.routes.draw do
resources :tasks
root 'welcome#index'
end
This sets the root URL of your application to the index
action of the Welcome
controller.
Step 7: Run Your Application
Restart the Rails server if it’s not already running:
rails server
Visit http://localhost:3000
in your browser to see your Rails application.
Step 8: Conclusion
This tutorial covers the essential steps to get started with Rails, including generating a scaffold, running migrations, starting the server, and customizing views. Rails provides many features and conventions to help you build powerful web applications efficiently. Explore the Rails Guides for more in-depth tutorials and documentation.