LoginSignup
1
0

More than 3 years have passed since last update.

RailsにおけるURLの直打ちを阻止する方法

Posted at

きっかけ

viewファイルに条件分岐を作っていても、そもそもUrlから直打ちされてしまうとページに飛ばれてしまうことに気づいたため。

結論

任意のコントローラーにbefore_actionを使って、アクションを起こす前段階の条件分岐を作っておく。

コード

items.controller.rb
class ItemsController < ApplicationController
  #before_actionを使って、コントーラーのアクションに飛ぶ前に条件分岐をかける
  before_action :correct_user, only: [:edit]
  before_action :item_find, only: [:show, :edit, :update, :destroy]

  def edit
  end

  private

  def item_params
    params.require(:item).permit(:title, :explain, :category_id, :condition_id, :price, :delivery_fee_id, :prefecture_id, :delivery_date_id, :image).merge(user_id: current_user.id)
  end
# before_actionをかけたメソッドでユーザーの選別を行っている
  def correct_user
    @item = Item.find(params[:id])
    if user_signed_in? && @item.user == current_user
      render :edit
    else 
      redirect_to root_path
    end
  end

補足

Urlに直打ちしているということは、ルーティングを経由して必ずコントローラーにページの開示を求めにくるから、コントーラーに記述する必要がある。MVCの流れを今一度再確認できた。

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