accepts_nested_attributes_for で、 "no implicit conversion of Symbol into Integer" エラーが出るときに確認すること
accepts_nested_attributes_forとは
Railsで関連テーブルを関連元と同時に保存する機能
accepts_nested_attributes_for の設定例
関連元モデル
class User < ApplicationRecord has_many :devices accepts_nested_attributes_for :devices end
関連先モデル
class Device < ApplicationRecord belongs_to :user end
controllerのストロングパラメータ
params.require(:user).permit( :name, :email, devices_attributes: [ :name ] )
起きたことと解決法
{ "user": { "name": "taro", "email": "aa@example.com", "devices_attributes": { "name": "phone" } } }
上記のパラメータを
InsomniaからPOSTした際に、
no implicit conversion of Symbol into Integer
が発生
一見意味がわかりませんでしたが、ストロングパラメータをよく見ると、devices_attributesが配列になっているではありませんか!
ということで、パラメータを
{ "user": { "name": "taro", "email": "aa@example.com", "devices_attributes": [ {"name": "phone"} ] } }
に変更するとスパッと通りました