簡體   English   中英

rails accepts_nested_attributes_for:reject_if無效

[英]rails accepts_nested_attributes_for :reject_if not working

我試圖覆蓋autosave參數,因為我認為無法完成。
我將has_shipping_addressOrderShippingAddress模型,現在我有:

#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM