gpt4 book ai didi

ruby-on-rails - RecordNotFound与accepts_nested_attributes_for和belongs_to

转载 作者:行者123 更新时间:2023-12-04 03:40:58 25 4
gpt4 key购买 nike

我懂了

ActiveRecord::RecordNotFound: Couldn't find Client with ID=3 for Order with ID=



尝试为现有客户提交订单时。通过键入以下内容,可以通过表单或控制台进行:
Order.new(:client_attributes => { :id => 3 })

payment_form.html.erb :
<%= semantic_form_for @order, :url => checkout_purchase_url(:secure => true) do |f| %>

<%= f.inputs "Personal Information" do %>

<%= f.semantic_fields_for :client do |ff| %>
<%= ff.input :first_name %>
<%= ff.input :last_name %>
<!-- looks like semantic_fields_for auto-inserts a hidden field for client ID -->
<% end %>

<% end %>
<% end %>

Order.rb :
class Order < ActiveRecord::Base
belongs_to :client
accepts_nested_attributes_for :client, :reject_if => :check_client

def check_client(client_attr)
if _client = Client.find(client_attr['id'])
self.client = _client
return true
else
return false
end
end
end
reject_if的想法来自 here,但我记录了该方法,甚至没有调用它!叫什么名字都没关系!

最佳答案

如果您只想使用现有客户创建一个新订单,而不修改客户,则需要分配ID。

Order.new(client_id: 3)
这是另一种方法,而无需重载 client_attributes=方法并且最干净
现在,新订单的ID为3的客户
如果您还想更新ant客户端的属性,则必须添加 client_attributes,例如:
Order.new(client_id: 3, client_attributes: { id: 3, last_order_at: Time.current })
参见2012年的 https://github.com/rails/rails/issues/7256

关于ruby-on-rails - RecordNotFound与accepts_nested_attributes_for和belongs_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9864501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com