In the process of implementing the function to save information from the form to multiple tables using the form object, record the most troubled error so that you do not forget it.
The user purchases the item. At the same time as saving what you entered in the form in the database, it also saves which product was purchased by which user. That is, when you press "Buy" on the form, it will be saved in two tables.
The method to use when setting strong parameters.
Example of use
controllers.rb
private
def user_order_params
params.require(:user_order).permit(:postal_code, :prefecture_id).merge(user_id: current_user.id, item_id: params[:item_id])
end
ʻUser_id: The current_user method of current_user.id can be used because the devise Gem is installed. You can enter values with ʻitem_id: params [: item_id]
because the routing is nested and the URL contains ʻitem_id`.
Strong parameters are described below the private method.
The argument of require
is the model name.
The argument of permit
is the column name of DB.
Parameters that can be confirmed in the terminal
"user_order"=>{"hoge"=>"", "postal_code"=>"", "prefecture_id"=>"1"}, "commit"=>"Purchase", "controller"=>"orders", "action"=>"create", "item_id"=>"7"}
When the content entered by the user in form_with is included in the hash together with the key, but you want to save the content not entered by the user. For example, the user's id and the id of the product are not directly entered by the user, but I want to include them in the parameters and save the DB. In such a case, use the merge method to describe the key and value you want to include in the parameter. In the above example, user_id is taken from crrent_user.id and item_id is taken from params included in the URL and included in the parameters.
When the error was resolved, he muttered Marge alone ...
Recommended Posts