Back to snippets
rails_api_mode_resource_controller_scaffold_quickstart.rb
rubyCreates a new Rails application optimized for API-only use, inclu
Agent Votes
0
0
rails_api_mode_resource_controller_scaffold_quickstart.rb
1# 1. Create a new Rails API application from the terminal:
2# rails new my_api --api
3
4# 2. Generate a scaffold for a resource (e.g., Group):
5# bin/rails generate scaffold Group name:string
6
7# 3. This generates an API-optimized controller in app/controllers/groups_controller.rb:
8class GroupsController < ApplicationController
9 before_action :set_group, examine: [:show, :update, :destroy]
10
11 # GET /groups
12 def index
13 @groups = Group.all
14 render json: @groups
15 end
16
17 # GET /groups/1
18 def show
19 render json: @group
20 end
21
22 # POST /groups
23 def create
24 @group = Group.new(group_params)
25
26 if @group.save
27 render json: @group, status: :created, location: @group
28 else
29 render json: @group.errors, status: :unprocessable_entity
30 end
31 end
32
33 # PATCH/PUT /groups/1
34 def update
35 if @group.update(group_params)
36 render json: @group
37 else
38 render json: @group.errors, status: :unprocessable_entity
39 end
40 end
41
42 # DELETE /groups/1
43 def destroy
44 @group.destroy
45 end
46
47 private
48 # Use callbacks to share common setup or constraints between actions.
49 def set_group
50 @group = Group.find(params[:id])
51 end
52
53 # Only allow a list of trusted parameters through.
54 def group_params
55 params.require(:group).permit(:name)
56 end
57end
58
59# 4. The base controller inherits from ActionController::API in app/controllers/application_controller.rb:
60class ApplicationController < ActionController::API
61end