#08:自分の記事だけ編集・削除 その1
ここでは、投稿したユーザーだけが自分の記事を編集・削除できるようにしましょう。そのために、contollerで、user_idが一致した時だけ、アクションを実行させます。
app/controllers/articles_controller.rbdef update
if @article.user_id == current_user.id
respond_to do |format|
if @article.update(article_params)
format.html { redirect_to @article, notice: 'Article was successfully updated.' }
format.json { render :show, status: :ok, location: @article }
else
format.html { render :edit }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
else
redirect_to @article, notice: "You don't have permission."
end
end
app/controllers/articles_controller.rbdef destroy
if @article.user_id == current_user.id
@article.destroy
msg = "Article was successfully destroyed."
else
msg = "You don't have permission."
end
respond_to do |format|
format.html { redirect_to articles_url, notice: msg }
format.json { head :no_content }
end
end