初めまして!某プログラミングスクールにて、フリマアプリを開発しました!
そこで、個人的に地獄のエラーを紹介したいと思います!
前提・実現したいこと
商品編集の際にUPDATEアクションを行いたい
商品の出品はできている。
発生している問題・エラーメッセージ
エラーGIF
https://gyazo.com/4dc564d739cad8f4ac8a0123371860bd
POST http://localhost:3000/items/1 400 (Bad Request)
Navigated to http://localhost:3000/items/1
Navigated to chrome-error://chromewebdata/
Navigated to http://localhost:3000/items/1/edit
edit:1 A cookie associated with a cross-site resource at http://google.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
該当コード
def edit
@item = Item.find(params[:id])
@images = @item.images
end
def update
@item = Item.find(params[:id])
@item.update(item_params)
end
private
def item_params
params.require(:item).permit( :name, :description, :category_id, :size_id, :brand_id, :prefecture_id, :condition_id, :delivery_charge_id, :delivery_way_id, :delivery_days_id, :price,images_attributes: [:image_url])
end
.sell_item_html
= render "/items/sheard/icon_header"
// 商品フォームヘッダー
.sell_form
.sell_form__main
%h2.sell_form__main__head
商品の情報を入力
.sell-main__form
= form_for(@item, url: item_path(@item), html: {method: "patch"}) do |f|
// 画像アップロード
.sell_form__main__box
.sell_upload_box
%h3.sell_upload_box__head
= f.label :image, "出品画像"
%span.form-require
必須
%p.info 最大10枚までアップロードできます
.sell_dropbox
ドラッグアンドドロップ
%br
またはクリックしてファイルをアップロード
.image-box__container
#image-box-1
.item-num-0#image-box__container
= f.fields_for :images do |i|
.input-area
= i.file_field :images,type: 'file', name: "item[images_attributes][][image_url]", value:"image_url", style: "display:none", id:"img-file",required: true
%label.input{for: "img-file",value: "patch"}
%i.fas.fa-camera
先に解決策!!
def edit
@item = Item.find(params[:id])
@images = @item.images
end
def update
@item = Item.find(params[:id])
@item.update(update_params)
end
private
def item_params
params.require(:item).permit( :name, :description, :category_id, :size_id, :brand_id, :prefecture_id, :condition_id, :delivery_charge_id, :delivery_way_id, :delivery_days_id, :price,images_attributes: [:image_url])
def update_params
params.require(:item).permit( :name, :description, :category_id, :size_id, :brand_id, :prefecture_id, :condition_id, :delivery_charge_id, :delivery_way_id, :delivery_days_id, :price,images_attributes: [:image_url, :id]
ここは開発時のDB設計等でテーブル等の入れるカラムの関係で多少違うかもしれません!
エラー原因
商品編集し、UPDATEを行う際にどの画像なのか?と言われてるみたいです!!
確かに言われてみれば、編集時は既存の画像がありますから、画像自体のIDが必要ですよね!!
パラメータが足りなくて400のエラーになっ手たみたいです!
ほんとにそれに気づかず、相当苦労しました!
参考記事
最後に
意外にcreateとupdate同じだろ!って思いながら実装しました。しかし、プログラミングはそう甘くないよと痛感したエラーでした。初歩的かもしれませんが、こういう基本的なところから勉強していかなければいかないと思いました!!