ruby on rails examples
Ruby on Rails is a popular web development framework written in the Ruby programming language. It follows the Model-View-Controller (MVC) architectural pattern and provides a set of conventions to make web development faster and easier. Here are some examples of Ruby on Rails code snippets along with explanations for each step:
- Creating a new Rails application:
- Open your terminal and navigate to the desired directory.
- Run the command
rails new myapp
to create a new Rails application named "myapp". This command generates the basic structure and files needed for a Rails application.
Generating a new model:
- Run the command
rails generate model User name:string email:string
to generate a new model named "User" with two attributes: "name" and "email". This command creates a migration file in the
db/migrate
directory, which defines the database schema for the "users" table.Running database migrations:
- Run the command
rails db:migrate
to apply pending database migrations. This command creates the "users" table in the database based on the migration file generated in the previous step.
Creating a new controller:
- Run the command
rails generate controller Users index show
to generate a new controller named "Users" with two actions: "index" and "show". This command creates a new file
app/controllers/users_controller.rb
which contains the actions for handling requests related to users.Defining actions in the controller:
- Open the file
app/controllers/users_controller.rb
. Inside the
UsersController
class, define the actions: ```ruby def index @users = User.all enddef show @user = User.find(params[:id]) end
`` - The
indexaction fetches all the users from the database and assigns them to the instance variable
@users. - The
showaction finds a user by the
idparameter passed in the request and assigns it to the instance variable
@user`.Creating views:
- Create a new folder
app/views/users
if it doesn't already exist. - Inside the
app/views/users
folder, create two files:index.html.erb
andshow.html.erb
. - In the
index.html.erb
file, you can display the list of users using the@users
instance variable. In the
show.html.erb
file, you can display the details of a specific user using the@user
instance variable.Routing requests:
- Open the file
config/routes.rb
. - Add the following lines to define the routes for the
UsersController
actions:ruby get '/users', to: 'users#index' get '/users/:id', to: 'users#show'
These lines map the URLs
/users
and/users/:id
to theindex
andshow
actions of theUsersController
, respectively.Starting the Rails server:
- Run the command
rails server
orrails s
to start the Rails server. - This command starts the server and makes your Rails application accessible at
http://localhost:3000
.
These are just a few examples of using Ruby on Rails. The framework provides many more features and functionalities for building robust web applications.