質問編集履歴

1

tweetsコントローラーの追記

2020/12/01 04:19

投稿

shawn_709
shawn_709

スコア13

test CHANGED
File without changes
test CHANGED
@@ -207,3 +207,143 @@
207
207
 
208
208
 
209
209
  以上になります。ご助言いただけると幸いです。
210
+
211
+
212
+
213
+ ###追記
214
+
215
+ ```controller
216
+
217
+ #tweets
218
+
219
+
220
+
221
+ class TweetsController < ApplicationController
222
+
223
+ before_action :authenticate_user!, only: [:index, :new, :edit]
224
+
225
+ before_action :set_group
226
+
227
+ before_action :set_tweet, only: [:show, :edit, :update, :destroy]
228
+
229
+
230
+
231
+ def index
232
+
233
+ @tweets = @group.tweets.includes(:user).order("created_at DESC")
234
+
235
+ end
236
+
237
+
238
+
239
+ def new
240
+
241
+ @tweet = Tweet.new
242
+
243
+ end
244
+
245
+
246
+
247
+ def create
248
+
249
+ @tweet = @group.tweets.new(tweet_params)
250
+
251
+ if @tweet.save
252
+
253
+ redirect_to group_tweets_path(@group)
254
+
255
+ else
256
+
257
+ @tweets = @group.tweets.includes(:user)
258
+
259
+ render :new
260
+
261
+ end
262
+
263
+ end
264
+
265
+
266
+
267
+ def show
268
+
269
+ end
270
+
271
+
272
+
273
+ def edit
274
+
275
+ unless user_signed_in? && current_user.id == @tweet.user_id
276
+
277
+ redirect_to root_path
278
+
279
+ end
280
+
281
+ end
282
+
283
+
284
+
285
+ def update
286
+
287
+ if @tweet.update(tweet_params)
288
+
289
+ redirect_to group_tweets_path(@group)
290
+
291
+ else
292
+
293
+ render :edit
294
+
295
+ end
296
+
297
+ end
298
+
299
+
300
+
301
+ def destroy
302
+
303
+ if current_user.id == @tweet.user_id
304
+
305
+ @tweet.destroy
306
+
307
+ redirect_to group_tweets_path(@group)
308
+
309
+ else
310
+
311
+ render :index
312
+
313
+ end
314
+
315
+ end
316
+
317
+
318
+
319
+ private
320
+
321
+
322
+
323
+ def tweet_params
324
+
325
+ params.require(:tweet).permit(:content, :image).merge(user_id: current_user.id)
326
+
327
+ end
328
+
329
+
330
+
331
+ def set_group
332
+
333
+ @group = Group.find(params[:group_id])
334
+
335
+ end
336
+
337
+
338
+
339
+ def set_tweet
340
+
341
+ @tweet = @group.tweets.find(params[:id])
342
+
343
+ end
344
+
345
+
346
+
347
+ end
348
+
349
+ ```