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

質問編集履歴

1

controllerを追加しました. これで足りますでしょうか?

2020/06/12 02:11

投稿

sasaharukimedes
sasaharukimedes

スコア27

title CHANGED
File without changes
body CHANGED
@@ -130,10 +130,94 @@
130
130
 
131
131
  <% end %>
132
132
  ```
133
+ **app/controllers/users_controller.rb**
134
+ ```
135
+ class UsersController < ApplicationController
136
+ before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
137
+ before_action :correct_user, only: [:edit, :update]
138
+ before_action :admin_user, only: :destroy
133
139
 
140
+ def destroy
141
+ User.find(params[:id]).destroy
142
+ flash[:success] = "User deleted"
143
+ redirect_to users_url
144
+ end
134
145
 
146
+ def index
147
+ #@users = User.paginate(page: params[:page])
148
+ @users = User.where(activated: true).paginate(page: params[:page])
149
+ end
135
150
 
136
151
 
152
+ def show
153
+ @user = User.find_by(params[:id])
154
+ redirect_to root_url and return unless @user.activated?
155
+ @microposts = @user.microposts.paginate(page: params[:page])
156
+ end
157
+
158
+ def new
159
+ @user = User.new
160
+ end
161
+
162
+ def create
163
+ @user = User.new(user_params) # params[:user]実装は終わっていないことに注意!
164
+ #マスアサインメント脆弱性
165
+ if @user.save
166
+ @user.send_activation_email
167
+ flash[:info] = "Please check your email to activate your account."
168
+ redirect_to root_url
169
+ else
170
+ render 'new'
171
+ end
172
+ end
173
+
174
+ def edit
175
+ end
176
+
177
+ def update
178
+ if @user.update(user_params)
179
+ flash[:success] = "Profile updated"
180
+ redirect_to @user
181
+ #更新に成功した場合に扱う
182
+ else
183
+ render "edit"
184
+ end
185
+ end
186
+
187
+ private
188
+
189
+ def user_params
190
+ params.require(:user).permit(:name, :email, :password,
191
+ :password_confirmation)
192
+ end
193
+
194
+ # beforeアクション
195
+
196
+ # ログイン済みユーザーかどうか確認
197
+ def logged_in_user
198
+ unless logged_in?
199
+ store_location
200
+ flash[:danger] = "Please log in."
201
+ redirect_to login_url
202
+ end
203
+ end
204
+
205
+ # 正しいユーザーかどうか確認
206
+ def correct_user
207
+ @user = User.find(params[:id])
208
+ redirect_to(root_url) unless current_user?(@user)
209
+ end
210
+
211
+ #管理者かどうか確認
212
+ def admin_user
213
+ redirect_to(root_url) unless current_user.admin?
214
+ end
215
+ end
216
+ ```
217
+
218
+
219
+
220
+
137
221
  ### 試したこと
138
222
 
139
223
  errorではなく, failureなのが気になりtypoより,メソッドや変数がうまく機能していないのかと思いましたが,うまく自分では発見できませんでした.エラー文で検索して以下の方の記事を見つけましたが, いまいち発見がありませんでした. 一応載せておきます.