代码之家  ›  专栏  ›  技术社区  ›  andi

Rails接受\嵌套的\属性\用于:如果不工作则拒绝\u

  •  5
  • andi  · 技术社区  · 17 年前

    我放弃了试图超越 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 似乎做不到这是工作。不管价值是多少 有发货地址 是, save 方法仍在嵌套的 船舶地址 ,导致验证错误。

    我在这里做错什么了吗?这有点让人沮丧。

    1 回复  |  直到 16 年前
        1
  •  10
  •   andi    17 年前

    结果证明 :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 %>
    

    我希望这至少也能帮助其他人,因为这让我很沮丧。