前提・実現したいこと
ある投稿をしてその投稿を削除、編集する権限を投稿者だけにしたいと考えています。
現在は誰でも編集や削除ができる状態なので改善したいです。
今あるテーブルはpostsテーブル、usersテーブル、commentsテーブルです。
該当のソースコード
posts_controller
class PostsController < ApplicationController before_action :authenticate_user!, only: [:show, :create] def index @posts = Post.all.order(created_at: :desc) end def show @post = Post.find(params[:id]) @comment = Comment.new @comments = @post.comments end def new @post = Post.new end def create @post = Post.new(post_params) if @post.save redirect_to post_path(@post) else render 'new' end end def edit @post = Post.find(params[:id]) end def update @post = Post.find(params[:id]) if @post.update(post_params) redirect_to @post else render 'edit' end end def destroy @post = Post.find(params[:id]) @post.destroy redirect_to posts_path end private def post_params params.require(:post).permit(:title, :text, :img, :img_cache, :remove_img) end end end
show.html.erb
<div class="main"> <div class="container mg"> <div class="row"> <!-- cardここから --> <div class="card card-center col-sm-12 col-md-10 col-lg-6"> <div class="card-top"> <ul class="header"> <li class="header-left"> name </li> <li class="header-right"> <%= @post.title %> </li> </ul> </div> <hr /> <div class="card-body"> <div class="card-img"> <%= image_tag @post.img.url, :class => "main-img" if @post.img? %> </div> <hr /> <h6>依頼内容</h6> <hr /> <div class="show-inner"> <div class="card-text"> <%= @post.text %> </div> <div class="show-date"> <ul class="date-fact"> <li> <i class="icon"> <%= fa_icon 'calendar', class: "fa-calendar"%> </i> <time class="post-time"> <%= @post.created_at.to_s(:datetime_base)%> </time> </li> </ul> </div> <!-- この2つを投稿者だけに権限を与えたい。 --> <%= link_to '編集', edit_post_path%> <%= link_to '削除', post_path(@post), method: :delete, data: {confirm: "本当にいいですか"} %> <!-- ここまで --> </div> </div> </div> <!-- cardここまで --> <div class="comment-body col-sm-12 col-lg-6"> <div class="comment-index"> <h6 class="card-header card-comment font-center">コメント</h6> <%= render 'comments/comment' %> </div> <hr /> <div class="comment-form"> <p class="com-advise font-center">アドバイスを送ってみましょう</p> <%= render 'comments/form' %> </div> </div> </div> </div> </div>
試したこと
show.htmlの削除と編集を
<% if user_signed_in? && @post.user_id == current_user.id %>
<% end %>
で括ってみたがダメだった。
回答1件
あなたの回答
tips
プレビュー