微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐