LoginSignup
0
3

More than 3 years have passed since last update.

複数モデルにデータを保存したい

Last updated at Posted at 2020-07-29

某メルカリのコピーサイトを作成中。
商品の画像登録にて、複数の画像登録となるとカラムが増えて美しくないので
別モデルでimageテーブルを作成することに

fields_for

form_for内で異なるモデルを編集できるようになる。

例:Productモデルに紐付くImageモデル

これを使うとform_withとかで別モデルに保存とかできるようになるっぽい
アソシエーションとかで紐づいてることが前提

Model

product(商品)とimageは1対多
accepts_nested_attributes_for で一緒に保存したいモデルを指定

product.rb
class Product < ApplicationRecord
  has_many :images
  accepts_nested_attributes_for :images
end



imageとproduct(商品)は多対一となってます
複数保存する場合は mount_uploaders と複数形にする必要があるので注意

image.rb
class Image < ApplicationRecord
  belongs_to :product
  mount_uploaders :image, ImageUploader
end

Controller

newアクションで build を使用することでfield_forが使用可能に

build

親モデルとアソシエーションを組んでいる子モデルのインスタンスを生成できるメソッド

みたいです。ちなみにhas_many(1対多)であれば

インスタンス変数.子モデル.build

で問題ありませんが、belongs_to や has_one では .build の表記では使えないらしく

親モデル.build_子モデル  例) @product.build_image

となるそうです

products.controller.rb
  def new
    @product = Product.new
    @product.images.build
  end

  def create
    @product = Product.create(product_params)
  end

  def product_params
    params.require(:product).permit(images_attributes: {image: []})
  end

またパラメーター内では
モデル名_attributes: と記述します

これも送るデータが一つか複数かで記述が変わり、一つの場合は

images_attributes: [:image]

こんな感じ

View

html.haml
    .Contents
      = form_with model: @product, html: {class: "Form"}, local: true do |f|
        .InputPhoto
          .InputPhoto__DropArea
            = f.fields_for :images do |c|
              = c.label :image
              = c.file_field :image, multiple: true

これでとりあえず画像の保存は完了!

次はjqueryか...


参考記事
https://qiita.com/kouuuki/items/5daf2b5f34273d8457f7
https://qiita.com/nakasato_minami/items/5015319292c9f8a93f34
https://qiita.com/mihou/items/2d7504c0bf98d07a95c3
ありがとうございました!!!

0
3
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
0
3