LoginSignup
28
31

More than 3 years have passed since last update.

rails 他人の詳細ページを編集不可にする際の注意点

Posted at

かなり基本的なところですが、今回アプリを完成させたと思ったら、
自分自身忘れていた箇所だったため、メモします。

また、今回はdeviceを使用して作成してます。

他人のデータを編集不可へ

複数人のユーザーが存在するアプリケーションでは自分のマイページや投稿内容を他人に変更できないように編集アイコンをログインしているユーザ以外表示されないようにしました。

     <% if @user.id == current_user.id %>
        <%= link_to edit_user_path(current_user.id) do %>
            <div class= " edit btn btn-outline-secondary btn-default btn-block" ><span class="glyphicon glyphicon-wrench" aria-hidden="true"></span></div>
        <% end %>
        <% end %>

<% if @user.id == current_user.id %>が肝。

これでOKと思いましたが、これでは自力で直接URLに打つと編集できてしまうということを見逃してました。。

ということでコントローラーないにも下記記載。

     def edit
         @book = Book.find(params[:id])
         if @book.user == current_user
            render "edit"
          else
            redirect_to books_path
          end
       end  

これで自分以外のユーザーが直接入力しても編集ページへいかず、一覧ページに飛ぶようにできました。

28
31
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
28
31