This article is written in words that the poster can understand in order to review what he has learned.
Strong parameters are those that have a specified key and can be restricted to receive only parameters.
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.
-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
-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
#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.
#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.
#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)
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
If you have any suggestions, I would appreciate it if you could let me know for your study.
Recommended Posts