RecordNotFound with accepts_nested_attributes_for and belongs_to

不想你离开。 提交于 2019-12-04 09:53:41
manafire

Fixed the issue by overloading the client_attributes= method, as described here:

  def client_attributes=(client_attrs)    
    self.client = Client.find_or_initialize_by_id(client_attrs.delete(:id))
    self.client.attributes = client_attrs
  end

If you only want a new Order with an existing client, without modifying the client, you need to assign the id.

Order.new(client_id: 3)

This is another way to do this without overloading the client_attributes= method and cleanest

The new Order now has the client with ID 3

If you also want to update ant client's attributes you must add the client_attributes, for example:

Order.new(client_id: 3, client_attributes: { id: 3, last_order_at: Time.current })

Had the same error creating a new Thing for existing model with has_many and belongs_to relations.

Fixed it by adding a hidden field for the id of the existing model, for instance User, to the form.

= form.input :user_id, as: :hidden

Then new Thing was created without the error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!