ruby-on-rails – 使用accepts_nested_attributes_for和belongs_
发布时间:2020-12-17 03:28:24 所属栏目:百科 来源:网络整理
导读:我明白了 ActiveRecord::RecordNotFound: Couldn’t find Client with ID=3 for Order with ID= 在尝试为现有客户提交订单时.这通过键入以下内容通过表单或控制台进行: Order.new(:client_attributes = { :id = 3 }) payment_form.html.erb: %= semantic_f
我明白了
在尝试为现有客户提交订单时.这通过键入以下内容通过表单或控制台进行: 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |