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?

rails params.expectの罠

Posted at

子レコードを一緒に保存しようとしてparams.expectの送信処理でエラーになった。

ActionController::ParameterMissing (param is missing or the value is empty or invalid: user):

ひとまず下のようにすれば成功する
子レコード単一送信(has_one関連)

users_controller.rb

def user_params
  params.expect(
    user: [
      user_detail_attributes: %i[address name hobby]
    ]
  )
end

子レコード複数モデル送信(両方ともhas_many関連)

users_controller.rb

def user_params
  params.expect(
    user: [
      user_families_attributes: [%i[id family_id]],
      user_friends_attributes: [%i[id friend_id]]
    ]
  )
end

考察

一応下にサイトはありますが英語なので読みたくないため考察で片付ける。

両方に()で示したがおそらく子レコードが複数ある時は余分に[]をつける必要があると思われる。
まあ単数モデルは絶対1つしか送信されないだろうから配列の[]で囲む必要ないだろという意味だと思う。
自分はhas_many関連モデルのコントローラーをhas_oneの方にコピペしてしまってこの事態に遭遇してしまった。

以上です。
凝った記事ではないですが、参考になったら "いいね" お願いします

参考

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?