5
0

More than 3 years have passed since last update.

Controller createアクション ストロングパラメーター

Last updated at Posted at 2020-01-29

Controller createアクション

ストロングパラメーターとは

Web画面から送られてきたデータを保存(create)する時に、安全に保存する仕組み。
"groups_controller.rb"のprivateよりも下の部分。

groups_controller.rb

  def create
    @group = Group.new (group_params)  #paramsメソッドを使用。 ストロングパラメータを引数として記述。
    if @group.save
      redirect_to root_path, notice: "グループが作成されました"  #cretaeされたらrootに移動。
    else
      render :new
    end
  end
  ・・・
  (省略)
  ・・・
private  #まずはprivateを記述。
  def group_params  #privateを記述してにストロングパラメーターを定義。
    params.require(:group).permit(:name, user_ids: [])  #reguireメソッドとpermitメソッドを使用
  end

params

送られてきた値を受け取るメソッド

.requireと.permit

requireメソッドでオブジェクト名を定義する。
permitメソッドで保存処理を許可する項目のキーを記述。

これで、Web上から悪意のあるデータが送られてきたとしても、許可している項目しか保存処理されない。

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