rails accepts_nested_attributes_for:reject_if无效

时间:2009-06-24 10:14:35

标签: ruby-on-rails activerecord nested nested-forms

我试图覆盖autosave参数,因为我觉得无法完成。
我将has_shipping_addressOrder移到ShippingAddress模型,现在我已经:

#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方法,从而导致验证错误。

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

1 个答案:

答案 0 :(得分: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 %>

我希望至少这对其他人也有帮助,因为对我来说这一点非常令人沮丧。