1) Complete the quick start guide:
https://localboyfrommadurai.blogspot.com/2021/03/ruby-on-rails-quick-start.html
2) Open Gemfile and the following line
gem 'kaminari'
This library helps for pagination
3) Install the gem:
bundle install
4) Modify app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
end
Adding this will allow the requests such as PUT, POST and DELETE calls without session authentication.
5) Modify config/routes.rb
Rails.application.routes.draw do
get 'users(/:page_no)' => 'users#list', :defaults => { :page_no => 1 }
delete 'users/:user_id' => 'users#delete'
put 'users/:user_id' => 'users#update'
post 'users' => 'users#create'
end
6) Modify app/controllers/users_controller.rb
class UsersController < ApplicationController
def update
params.require(:name)
user = User.find(params[:user_id])
if user
user.update(name: params[:name])
render json: {}, status: :ok
return
end
render json: {}, status: :not_found
end
def create
params.require(:name)
user = User.create({:name => params[:name]})
render json: user, status: :ok
end
def list
@users = User.page(params[:page_no]).per(5)
render 'users/list'
end
def delete
User.delete(params[:user_id])
render json: {}, status: :no_content
end
end
7) Modify app/views/users/list.html.erb
<h1>Users</h1>
<ul>
<% @users.each do |user| %>
<li>
<div><b>ID: </b><%= user.id %> </div>
<div><b>Name: </b><%= user.name %> </div>
</li>
<% end %>
</ul>
Results:
Happy coding :)