@@ -151,6 +151,97 @@ This will do three main things for you:
151
151
- Configure the generators to skip generating views, helpers, and assets when
152
152
you generate a new resource.
153
153
154
+ ### Generating a New Resource
155
+
156
+ To see how our newly created API handles generating a new resource, let's create
157
+ a new Group resource. Each group will have a name.
158
+
159
+ ``` bash
160
+ $ bin/rails g scaffold Group name:string
161
+ ```
162
+
163
+ Before we can use our scaffolded code, we need to update our database scheme.
164
+
165
+ ``` bash
166
+ $ bin/rails db:migrate
167
+ ```
168
+
169
+ Now if we open our ` GroupsController ` , we should notice that with an API Rails
170
+ app we are rendering JSON data only. On the index action we query for ` Group.all `
171
+ and assign it to an instance variable called ` @groups ` . Passing it to ` render ` with the
172
+ ` :json ` option will automatically render the groups as JSON.
173
+
174
+ ``` ruby
175
+ # app/controllers/groups_controller.rb
176
+ class GroupsController < ApplicationController
177
+ before_action :set_group , only: %i[ show update destroy ]
178
+
179
+ # GET /groups
180
+ def index
181
+ @groups = Group .all
182
+
183
+ render json: @groups
184
+ end
185
+
186
+ # GET /groups/1
187
+ def show
188
+ render json: @group
189
+ end
190
+
191
+ # POST /groups
192
+ def create
193
+ @group = Group .new (group_params)
194
+
195
+ if @group .save
196
+ render json: @group , status: :created , location: @group
197
+ else
198
+ render json: @group .errors, status: :unprocessable_entity
199
+ end
200
+ end
201
+
202
+ # PATCH/PUT /groups/1
203
+ def update
204
+ if @group .update(group_params)
205
+ render json: @group
206
+ else
207
+ render json: @group .errors, status: :unprocessable_entity
208
+ end
209
+ end
210
+
211
+ # DELETE /groups/1
212
+ def destroy
213
+ @group .destroy
214
+ end
215
+
216
+ private
217
+ # Use callbacks to share common setup or constraints between actions.
218
+ def set_group
219
+ @group = Group .find(params[:id ])
220
+ end
221
+
222
+ # Only allow a list of trusted parameters through.
223
+ def group_params
224
+ params.require(:group ).permit(:name )
225
+ end
226
+ end
227
+ ```
228
+
229
+ Finally we can add some groups to our database from the Rails console:
230
+
231
+ ``` irb
232
+ irb> Group.create(name: "Rails Founders")
233
+ irb> Group.create(name: "Rails Contributors")
234
+ ```
235
+
236
+ With some data in the app, we can boot up the server and visit < http://localhost:3000/groups.json > to see our JSON data.
237
+
238
+ ``` json
239
+ [
240
+ {"id" :1 , "name" :" Rails Founders" , "created_at" : ... },
241
+ {"id" :2 , "name" :" Rails Contributors" , "created_at" : ... }
242
+ ]
243
+ ```
244
+
154
245
### Changing an Existing Application
155
246
156
247
If you want to take an existing application and make it an API one, read the
0 commit comments