5

我放弃了尝试覆盖autosave参数,因为我认为它无法完成。
我将其has_shipping_address从模型移到OrderShippingAddress模型,现在我有了:

#the models..
class Order < ActiveRecord::Base

  belongs_to :billing_address
  belongs_to :shipping_address 

  accepts_nested_attributes_for :billing_address
  accepts_nested_attributes_for :shipping_address, :reject_if => proc { |attributes| attributes["has_shipping_address"] != '1' }

  def after_initialize                       
    self.build_billing_address unless billing_address
    self.build_shipping_address unless shipping_address
  end

end

class ShippingAddress < OrderAddress
  attr_accessor :has_shipping_address  
end

class OrderAddress < ActiveRecord::Base
  validates_presence_of :name
  #more validations here..
end   

#the view
<% form_for @order do |f| %>
  #...
  <% f.fields_for :shipping_address do |addr_f| %>
    <%= addr_f.check_box :has_shipping_address %>
    <%= addr_f.text_field :name %>
    #more fields for the address..
  <% end %>
<% end %>

问题是它:reject_if似乎没有做它的工作。不管值has_shipping_address是什么,save方法仍然在嵌套调用ShippingAddress,导致验证错误。

我在这里做错了吗?这有点令人沮丧。

4

1 回答 1

10

原来:reject_if没有工作,因为我正在订单回调中shipping_address构建嵌套。after_initialize将其移至视图(或辅助方法)后,它按预期工作。

def after_initialize                       
  self.build_billing_address unless billing_address
end

#the view is now
<% form_for @order do |f| %>
  #...
  <% @order.build_shipping_address unless @order.shipping_address %>
  <% f.fields_for :shipping_address do |addr_f| %>
    <%= addr_f.check_box :has_shipping_address %>
    <%= addr_f.text_field :name %>
    #more fields for the address..
  <% end %>
<% end %>

我希望至少这对其他人也有帮助,因为我很沮丧。

于 2009-06-25T09:45:49.443 回答