0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Rails】accepts_nested_attributes_forを使って子モデルも保存

Last updated at Posted at 2022-11-21

まえがき

推奨されてないaccepts_nested_attributes_forを使わずに、親モデルに紐づくレコードの一括保存をしようとしたが結局うまくいかずaccepts_nested_attributes_forを使ったときの備忘録。

以下の記事を参考にしましたが、私はうまくいきませんでした。

accepts_nested_attributes_forを使ってみる

親クラスにaccepts_nested_attributes_for :テーブル名を追加

event.rb
class Event < ApplicationRecord
  has_many :possible_dates, dependent: :restrict_with_exception

  accepts_nested_attributes_for :possible_dates
end
possible_dates.rb
class PossibleDate < ApplicationRecord
  belongs_to :event
end
eventscontroller.rb
class Api::EventsController < ApplicationController

  def create
    event = Event.new(event_params.merge(hashed_url: SecureRandom.uuid))
    if event.save
      render json: event
    else
      render json: event.errors, status: :unprocessable_entity
    end
  end

  private

  def event_params
    params.require(:event).permit(
      :name,
      :category_id,
      :user_id,
      :is_public,
      :description,
      possible_dates_attributes: %i(id proposed_at)
    )
  end
end

もしaccepts_nested_attributes_forメソッドを使わずに実装できる方法があれば教えていただきたいです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?