[英]Rails how to reject_if when accepts_nested_attributes_for
[英]rails accepts_nested_attributes_for :reject_if not working
我试图覆盖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
的值是什么,仍然会在嵌套的ShippingAddress
上调用save
方法,从而导致验证错误。
我在这里做错了吗? 这有点令人沮丧。
结果是:reject_if
没有用,因为我在订单的after_initialize
回调中构建了嵌套的shipping_address
。 将其移动到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 %>
我希望至少这对其他人也有帮助,因为我一直很难以理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.