我放弃尝试覆盖 autosave
参数,因为我认为它无法完成。
我搬了has_shipping_address
来自 Order
到 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
上调用方法,导致验证错误。我在这里做错了吗?这有点令人沮丧。
最佳答案
结果是 :reject_if
没有工作,因为我正在构建嵌套 shipping_address
在 after_initialize
订单回调。
将其移动到 View (或辅助方法)后,它按预期工作。
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 %>
我希望至少这也会对其他人有所帮助,因为弄清楚这一点让我非常沮丧。
关于ruby-on-rails - rails accepts_nested_attributes_for :reject_if not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1037505/