LoginSignup
1
2

More than 3 years have passed since last update.

fields_forについて

Posted at

はじめに

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テーブルに画像を保存することが可能になります。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2