Today we are going to discuss Ruby On Rails. This is my first blog about ROR. Rails is a server-side application framework written in Ruby. Rails is an MVC framework.
Here we will discuss how we can perform CRUD operations API in ROR with pagination while listing the data.
Step1
Create new rails project using the below command
rails new project
Step 2
Configure your database in database.yml inside the config folder
Step 3
Create a new database using the below command
rails db:create
Step 4
Create a model using the below command
rails g model <model_name>
Ex: rails g model users
Step 5
Creating a controller using the command belowrails g:controller <controller_name>
Ex: rails g controller users
Step 6
Configuring the routes in the routes.rb fileRails.application.routes.draw do
resources :users
end
Step 7
For listing the data using the pagination I am using kaminari gemStep 8
Now we are listing the data using the below set of code
def index
@user = User.order("id DESC") .page(params[:page]).per(params[:per_page])
@user_data = []
@user.each do |user|
@user_data.push(
id: user.id,
user_name: user.username,
password: user.password,
display_name: user.display_name,
created_at: user.created_at.strftime('%Y-%m-%d %H:%M:%S'),
)
end
render json: {
data: @user_data,
total: @user.total_count,
recordsFiltered: @user.total_count,
recordsTotal: @user.total_count
}
end
Step 9
Create a new user data
def create
@user = User.create(user_params)
render json: @user
end
Step 10
Show a user data
def show
@user = User.find(params[:id])
render json: @user
end
Step 11
Update a user data
def update
@user = User.find(params[:id])
@user.update_attributes(user_params)
render json: @user
end
Step 12
Destroy a user data
def destroy
@user = User.find(params[:id]).destroy
render json: {message: "Deleted"}
end
Step 13
Now we are creating the user params a the last
protected
def user_params
params.permit(
:username,
:password,
:display_name
)
end
Hence we completed the crud operations. You can check the full set of codes in my below Git Link . If you have any queries please contact me back
Comments
Post a Comment