Examples
Ruby Rails App
Building a Rails App
Ruby Rails app creates full-stack web UIs with MVC.
Introduction to Ruby on Rails
Ruby on Rails, or Rails, is a web application framework written in Ruby. It follows the Model-View-Controller (MVC) architecture, making it easier to build and maintain complex web applications. Rails is known for its convention over configuration approach, which simplifies the development process.
Setting Up a New Rails Application
Before you start, ensure you have Ruby and Rails installed on your system. You can create a new Rails application using the following command:
Navigate to your app directory:
Understanding the Rails Directory Structure
When you generate a new Rails application, it comes with a predefined directory structure:
- app/ - Contains the controllers, models, views, and assets.
- config/ - Holds the configuration files for the application.
- db/ - Contains database-related files.
- public/ - Serves static files directly.
- Gemfile - Specifies the gem dependencies for your application.
Generating a Controller
Controllers are responsible for managing the flow between the model and the view. You can generate a controller using the following command:
This command creates a HomeController
with an index
action and a corresponding view file.
Creating a Model
Models in Rails are used to interact with the database. To create a model, use:
This command generates a model Article
with string and text fields. After creating the model, run the migration to update the database:
Building Views
Views in Rails are templates that generate HTML. They are located in the app/views
directory. To display a list of articles, you can create an index.html.erb
file in app/views/articles
:
Connecting MVC Components
Now that you have a controller, model, and view, let's connect them. In the HomeController
, fetch the articles:
This code retrieves all articles from the database and makes them available to the index
view.
Conclusion
In this guide, we walked through the basics of setting up a Ruby on Rails app with MVC architecture. You learned how to create controllers, models, and views, and how to connect them to build a functional web application. As you continue to develop your Rails app, explore more features like routing, validations, and API integrations.
Examples
- Previous
- Database CRUD
- Next
- API Testing