はじめに
fields_forとはform内で異なるモデルを編集することができるようになるもの。
今回はitemテーブルとimageテーブルが1対多の関係の時にimageテーブルに画像を保存できるようにするために使用した。
使い方
new.html.haml
.item-contents__image
%label
.item-contents__image__box
.input-area
.item-contents__image__box__text
ドラッグアンドドロップ
またはクリックしてファイルをアップロード
#file-preview
= f.fields_for :images do |i|
=i.file_field :url, class: 'item-contents__image__drop-file', type: "file"
item.controller.rb
def new
@item = Item.new
@item.images.build
end
def create
Item.create(item_params)
redirect_to root_path, notice: '商品を出品しました'
end
private
def item_params
params.require(:item).permit(:name, :description, :price, images_attributes: [:url, :item_id])
end
item.rb
has_many :images
accepts_nested_attributes_for :images
image.rb
belongs_to :item
mount_uploader :url, ImageUploader
これらの記述をすることでimageテーブルに画像を保存することが可能になります。