ruby-on-rails – 使用accepts_nested_attributes_for和belongs_to的RecordNotFound

我明白了

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

解决方法

通过重载client_attributes =方法修复了问题,如 here所述:

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...