RecordNotFound 与 accepts_nested_attributes_for 和belongs_to [英] RecordNotFound with accepts_nested_attributes_for and belongs_to

查看:71
本文介绍了RecordNotFound 与 accepts_nested_attributes_for 和belongs_to的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白了

ActiveRecord::RecordNotFound: 无法为 ID=3 的订单找到 ID=3 的客户

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

尝试为现有客户提交订单时.这通过输入以下内容通过表单或控制台发生:

when trying to submit an Order form for an existing client. This happens through the form or the console by typing:

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 的想法来自 此处 但我记录了该方法,它甚至没有被调用!它的名字是什么并不重要!

The reject_if idea came from here but I logged the method and it's not even being called! It doesn't matter what its name is!

推荐答案

如果只想要一个已有客户端的新订单,不修改客户端,则需要分配id.

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)

这是另一种无需重载 client_attributes= 方法且最干净

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

新订单现在有 ID 为 3 的客户端

The new Order now has the client with ID 3

如果你还想更新ant客户端的属性,你必须添加client_attributes,例如:

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 })

参见 https://github.com/rails/rails/issues/7256 从 2012 年开始.

See https://github.com/rails/rails/issues/7256 from 2012.

这篇关于RecordNotFound 与 accepts_nested_attributes_for 和belongs_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆