teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

追記

2021/05/01 02:04

投稿

pay_561
pay_561

スコア26

title CHANGED
File without changes
body CHANGED
@@ -41,4 +41,91 @@
41
41
  <% end %>
42
42
  </div>
43
43
  ```
44
+
45
+ ##追記
46
+
47
+ ##posts_controller.rb
48
+ ```ここに言語を入力
49
+ class PostsController < ApplicationController
50
+ before_action :authenticate_user!
51
+ before_action :find_post, only: [:index, :show, :edit, :update, :destory]
52
+ before_action :force_redirect_unless_my_post, only: [:edit, :update, :destory]
53
+
54
+ def index
55
+ @posts = Post.all.order(created_at: :desc)
56
+ @posts = Post.page(params[:page]).per(25).order('updated_at DESC')
57
+ end
58
+
59
+ def show
60
+ @post = Post.find_by(id: params[:id])
61
+ end
62
+
63
+ def new
64
+ @post = Post.new
65
+ end
66
+
67
+ def edit
68
+ end
69
+
70
+ def create
71
+ @post = Post.new(post_params)
72
+ @post.user = current_user
73
+ if @post.save!
74
+ redirect_to root_path, notice: '投稿成功!!'
75
+ else
76
+ render :new
77
+ end
78
+ end
79
+
80
+ def update
81
+ if @post.update(post_params)
82
+ redirect_to root_path, notice: '投稿を更新しました。'
83
+ else
84
+ render :edit
85
+ end
86
+ end
87
+
88
+ def destory
89
+ if @post.destory
90
+ redirect_to root_path, notice: '投稿を削除しました。'
91
+ else
92
+ redirect_to root_path, alert: '投稿が削除できませんでした。'
93
+ end
94
+ end
95
+
96
+ private
97
+
98
+ def post_params
99
+ params.require(:post).permit(
100
+ :thumbnail,
101
+ :title,
102
+ :version,
103
+ :code,
104
+ :description,
105
+ :video,
106
+ images: [],
44
-
107
+ )
108
+ end
109
+
110
+ def find_post
111
+ @post = Post.find_by(params[:id])
112
+ end
113
+
114
+ def force_redirect_unless_my_post
115
+ return redirect_to root_path, alert: '自分の投稿ではありません' if @post.user != current_user
116
+ end
117
+ end
118
+
119
+ ```
120
+ ##profiles_controller.rb
121
+ ```ここに言語を入力
122
+ class ProfilesController < ApplicationController
123
+ before_action :authenticate_user!
124
+
125
+ def show
126
+ @profile = current_user
127
+ end
128
+
129
+ private
130
+ end
131
+ ```