LoginSignup
0
0

More than 3 years have passed since last update.

他ユーザーの投稿編集画面に行けないようにする

Last updated at Posted at 2020-11-11

環境

・Rails 5
・deviceを用いてログイン機能を実装済み

ログインしていないユーザーを投稿編集画面に行けないようにする

ログインしている時としていない時で表示画面を変える

view.rb
<% if user_signed_in? %>

ログインしていない場合ログイン画面に飛ぶ

controller.rb
before_action :authenticate_user!

他ユーザーの投稿編集画面に行けないようにする

view側だけに記述した場合だと、urlを直接打つと変更できてしまうのでcontroller側にも記述する。

controller.rb
@book = Book.find(params[:id])
  if @book.user == current_user
    render "edit"
  else
    redirect_to books_path
  end
view.rb
<% if @book.user == current_user %>
  〜〜〜〜〜
<% end %>

違う方法

controller.rb
  before_action :ensure_correct_user, only: [:edit, :update]

  def ensure_correct_user
    unless @user == current_user
      redirect_to user_path(current_user)
    end
  end

if文 → もしも、評価が真(true)であれば○○する
unless文 → もしも、評価が偽(false)であれば○○する

最後に

筆者は初学者なので間違っている部分や説明不足などあると思います。その際には指摘していただけると幸いです。

参考文献

0
0
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
0
0