質問編集履歴

2

Ruby, Ruby on Railsのタグを追加した。

2017/01/05 05:01

投稿

Miracle
Miracle

スコア54

test CHANGED
File without changes
test CHANGED
File without changes

1

メソッドの記述をより詳細にした。

2017/01/05 05:01

投稿

Miracle
Miracle

スコア54

test CHANGED
@@ -1 +1 @@
1
- 【rails】コントローラのdestroyアクションについて
1
+ 【rails】コントローラのdestroyアクションの例外処理について
test CHANGED
@@ -1,16 +1,20 @@
1
- railsのコントローラで、newやupdateはよく
1
+ railsのコントローラで、createやupdateアクションではよく
2
2
 
3
3
  ```
4
4
 
5
- if hoge.save(もしくはupdate)
5
+ def create
6
6
 
7
- redirect_to hoge_path
7
+ hoge = Hoge.new(hoge_params) #hoge_paramsがprivateで定義されている
8
8
 
9
- else
9
+ if hoge.save(もしくはupdate)
10
10
 
11
- render :new
11
+ redirect_to root_path, notice: '保存に成功しました。'
12
12
 
13
+ else
14
+
15
+ render :new, alert: '保存に失敗しました。'
16
+
13
- end
17
+ end
14
18
 
15
19
  ```
16
20
 
@@ -18,9 +22,15 @@
18
22
 
19
23
  ```
20
24
 
21
- hoge.destroy
25
+ def destroy
22
26
 
27
+ hoge = Hoge.find(params[:id])
28
+
29
+ hoge.destroy
30
+
23
- redirect_to hoge_path
31
+ redirect_to root_path, notice: '削除に成功しました。'
32
+
33
+ end
24
34
 
25
35
  ```
26
36
 
@@ -30,4 +40,4 @@
30
40
 
31
41
  destroyアクションだと、なぜ例外処理が必要無いのでしょうか?
32
42
 
33
- 単純に、「削除できない場合が無い」というのが理由でしょうか?
43
+ 単純に、「削除できない場合が無い」というのが理由なのでしょうか?