[Ruby] Strong parameters [require] [permit] [merge] How to use Role

Introduction

This article is written in words that the poster can understand in order to review what he has learned.

1. Role

Strong parameters are those that have a specified key and can be restricted to receive only parameters.

2. Reason to use

Unintended data storage by limiting the parameter data received. To avoid updates. This time, we will introduce an example assuming a flea market app that sells products.

3. Basic configuration and usage

-The basic configuration is as follows.

#・ ・ ・ Omitted
 def new
    @item = Item.new
  end

 def create
   @item = Item.new(item_params)
 end

 private

 def item_params
   params.require(:item).permit(:name, :explanation, :category_id, :status_id, :delivery_fee_id, :shipping_region_id, :shipping_day_id, :selling_price, :image).merge(user_id: current_user.id)
 end

how to use

-Strong parameters are defined as private methods. -Readability is improved by setting ** item_params ** </ font> as shown below. ** update action ** </ font> to update the data after saving with ** create action ** </ font> Make changes so you can put together your description! !!

 def create
   @item = Item.new(item_params)← Here
 end

4. Limit value

4-1.require (model name)

#Example of use
params.require(:Model name)

params.require(:item)

#All the data contained in the item model is saved.
Use permit when you want to limit the values you want to save by column name in the specified model.

4-2.permit (: key 1, key 2 ...)

#Example of use
params.permit(:Key 1, :Key 2....)

params.require(:item).permit(:name, :explanation, :category_id, :status_id, :delivery_fee_id, :shipping_region_id, :shipping_day_id, :selling_price, :image)

#Even in the specified model, when you want to limit the value you want to save, limit the column name with permit.

4-3.merge (: foreign key you want to merge, etc.)

#Example of use: When you want to link the information of the user who listed the product
params.merge(user_id: current_user.id)

params.require(:item).permit(:name, :explanation, :category_id, :status_id, :delivery_fee_id, :shipping_region_id, :shipping_day_id, :selling_price, :image).merge(user_id: current_user.id)

Caution

You can use ** current_user.id ** because you are using ** devise **. </ font> There was an article that was helpful, so I will share it.

List of helper methods available in Rails devise https://qiita.com/tobita0000/items/866de191635e6d74e392

5. Finally

If you have any suggestions, I would appreciate it if you could let me know for your study.

Recommended Posts