Ruby on rails rails接受\u嵌套的\u属性\u:如果不工作,则拒绝\u
我放弃了尝试重写Ruby on rails rails接受\u嵌套的\u属性\u:如果不工作,则拒绝\u,ruby-on-rails,activerecord,nested,nested-forms,Ruby On Rails,Activerecord,Nested,Nested Forms,我放弃了尝试重写autosave参数,因为我认为这是不可能的。 我将has_shipping_地址从订单移动到shipping地址型号,现在我有: #the models.. class Order < ActiveRecord::Base belongs_to :billing_address belongs_to :shipping_address accepts_nested_attributes_for :billing_address accepts_nes
autosave
参数,因为我认为这是不可能的。
我将
has_shipping_地址
从订单
移动到shipping地址
型号,现在我有:
#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 %>
#模型。。
类顺序proc{| attributes | attributes[“has _shipping _address”]!='1'}
初始化后的def
自行生成计费地址,除非计费地址
自行生成装运地址,除非装运地址
结束
结束
类ShippingAddress
问题是:如果似乎不起作用,就拒绝\u。无论has_shipping_address
的值是什么,嵌套的ShippingAddress
仍会调用save
方法,从而导致验证错误
我做错什么了吗?这有点令人沮丧。结果是:如果不起作用,则拒绝\u,因为我在初始化订单的回调后在中构建嵌套的发货地址。
将其移动到视图(或助手方法)后,它将按预期工作
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 %>
初始化后的def
自行生成计费地址,除非计费地址
结束
#现在的景色很美
#...
#地址的更多字段。。
我希望这至少也能帮助其他人,因为这让我很沮丧