LoginSignup
2
7

More than 3 years have passed since last update.

投稿したユーザーのみ編集・削除を許可したい

Posted at

投稿したユーザーのみ編集・削除

【例】モデルをTweetとします。

app/views/tweets/index.html.erb
〜省略〜
<% if user_signed_in? && current_user.id == tweet.user_id %>
            <li>
              <%= link_to '編集', "/tweets/#{tweet.id}/edit", method: :get %>
            </li>
            <li>
              <%= link_to '削除', "/tweets/#{tweet.id}", method: :delete %>
            </li>
          <% end %>
〜省略〜

上記で「ユーザーがログインしている」かつ「投稿したユーザーである投稿だけに許可」となります。
current_user.id == tweet.user_idにより、ログイン中ユーザーのidと投稿したユーザーのidが一致すれば、編集・削除の表示を許可しました。
user_signed_in?はユーザー登録しているか?
currentは現在なのでcurrent_user.idはログイン中
tweet.user_idはどのユーザーのidか
&&は"かつ"==は"等しい"という意味です。
showアクションにも記述します。
【例】

app/views/tweets/show.html.erb
〜省略〜
<% if user_signed_in? && current_user.id == tweet.user_id %>
            <li>
              <%= link_to '編集', "/tweets/#{tweet.id}/edit", method: :get %>
            </li>
            <li>
              <%= link_to '削除', "/tweets/#{tweet.id}", method: :delete %>
            </li>
          <% end %>
〜省略〜

さっきのとは少し違いcurrent_user.id == @tweet.user_idという条件を含むif文で、未ログイン時や自分の投稿ではない時は非表示となるように記述しました。

2
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
7