LoginSignup
0
0

More than 3 years have passed since last update.

【Ruby On Rails】include?を使ってparamsの中身を検索する方法

Posted at

備忘録です。

検索方法

params.require(:モデル名).permit(:カラム名).to_s.include?("検索ワード")

to_sと書くことで、"permit(:カラム名)" のカラムに含まれたデータを文字列として扱ってくれます。

updateできる場合の例

例①

controller.rb

  def update
    if params.require(:fridge).permit(:icecream).to_s.include?("ガリガリ君")
      @fridge.update(fridge_params) 
      redirect_to root_path
    else
      render :edit
    end
  end

  def fridge_params
    params.require(:fridge).permit(:vegetable, :meat, :icecream).merge(user_id: current_user.id)
  end

params
Parameters: {"authenticity_token"=>"XXX==", "fridge"=>{"vegetable"=>"茄子", "meat"=>"牛肉", "icecream"=>"ガリガリ君"}

例②

controller.rb

  def update
    if params.require(:fridge).permit(:icecream).to_s.include?("雪見だいふく")
      @fridge.update(fridge_params) 
      redirect_to root_path
    else
      render :edit
    end
  end

  # fridge_paramsは以後省略
params
Parameters: {"authenticity_token"=>"XXX==", "fridge"=>{"vegetable"=>"ピーマン", "meat"=>"豚肉", "icecream"=>"雪見だいふく"}

例③

controller.rb

  def update
    if params.require(:fridge).permit(:meat).to_s.include?("鶏肉")
      @fridge.update(fridge_params) 
      redirect_to root_path
    else
      render :edit
    end
  end

params
Parameters: {"authenticity_token"=>"XXX==", "fridge"=>{"vegetable"=>"トマト", "meat"=>"豚肉と鶏肉", "icecream"=>"ジャンボ"}

updateできない場合の例

例①

controller.rb

  def update
    if params.require(:fridge).permit(:vegetable).to_s.include?("もやし")
      @fridge.update(fridge_params) 
      redirect_to root_path
    else
      render :edit
    end
  end

params
Parameters: {"authenticity_token"=>"XXX==", "fridge"=>{"vegetable"=>"ニラ", "meat"=>"牛肉", "icecream"=>"爽"}

例②

controller.rb

  def update
    if params.require(:fridge).permit(:vegetable).to_s.include?("ブロッッッコリー")
      @fridge.update(fridge_params) 
      redirect_to root_path
    else
      render :edit
    end
  end

params
Parameters: {"authenticity_token"=>"XXX==", "fridge"=>{"vegetable"=>"ブロッコリー", "meat"=>"羊肉", "icecream"=>"爽"}

例③

controller.rb

  def update
    if params.require(:fridge).permit(:icecream).to_s.include?("ジャイアントコーン")
      @fridge.update(fridge_params) 
      redirect_to root_path
    else
      render :edit
    end
  end

params
Parameters: {"authenticity_token"=>"XXX==", "fridge"=>{"vegetable"=>"じゃがいも", "meat"=>"人肉", "icecream"=>"ジャイアンとコーン"}

注意点

コントローラーで保存したい文字列を制限しているだけで、DBでの保存を弾いてくれるわけではありません。使い方には注意が必要かもしれないです。

参考記事

https://stackoverflow.com/questions/57625775/how-to-check-if-parameters-string-contains-a-substring
https://stackoverflow.com/questions/5629402/how-to-test-if-parameters-exist-in-rails/5629506

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