rails new my-app --api --database=postgresql -T
This step is for creating a very basic level of model for us to work in. If you know already, or wish to apply your own custom models with relationships you can skip this step.
- Create an User model
rails generate model User name:string
- Create a Post model - association with User
rails generate model Post title:string body:text user:belongs_to
- Migrate the models
rails db:migrate
Gemfile
group :development do
gem 'faker'
end
Install gem
bundle install
db/seeds.rb
5.times do
user = User.create({name: Faker::Name.name})
user.posts.create({title: Faker::Book.title, body: Faker::Lorem.sentence})
end
rails db:seed
Nesting the API routes config/routes.rb
namespace 'api' do
namespace 'v1' do
resources :posts
resources :users
end
end
Create an api folder inside App/controllers folder. Then create v1 folder inside api folder which you created. Then create controllers. Note - You do not have to create the controllers with rails generate controllers. Create the controllers simply by creating a new file. controllers/api/v1/users_controller.rb
module Api
module V1
class UsersController < ApplicationController
end
end
end
controllers/api/v1/posts_controller.rb
module Api
module V1
class PostsController < ApplicationController
end
end
end
controllers/api/v1/posts_controller.rb
module Api
module V1
class PostsController < ApplicationController
def index
@posts = Post.order('created_at DESC')
render json: {status: 'SUCCESS', message: 'Loaded posts', data:@posts}, status: :ok
end
def show
@post = Post.find(params[:id])
render json: {status: 'SUCCESS', message: 'Loaded posts', data:@post}, status: :ok
end
def create
@post = Post.new(post_params)
if @post.save
render json: {status: 'SUCCESS', message: 'Post is saved', data:@post}, status: :ok
else
render json: {status: 'Error', message: 'Post is not saved', data:@post.errors}, status: :unprocessable_entity
end
end
def update
@post = Post.find(params[:id])
if @post.update_attributes(post_params)
render json: {status: 'SUCCESS', message: 'Post is updated', data:@post}, status: :ok
else
render json: {status: 'Error', message: 'Post is not updated', data:@post.errors}, status: :unprocessable_entity
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
render json: {status: 'SUCCESS', message: 'Post successfully deleted', data:@post}, status: :ok
end
private
def post_params
params.permit(:title, :body)
end
end
end
end
After updating the code, use software such as Postman to check whether all the routes are working properly.