Rails accepts_nested_attributes_for: reject_if not working

I tried to override the parameter autosaveas I think it is not possible.
I moved has_shipping_addressfrom Orderto model ShippingAddress, and now I have:

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

The problem is that :reject_ifit doesn't seem to do the job. No matter what the meaning has_shipping_address, the method saveis still invoked on the nested one ShippingAddress, which leads to validation errors.

Am I doing something wrong here? This is a little frustrating.

+3
source share
1 answer

: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 %>

, , , - , .

+9

Source: https://habr.com/ru/post/1711163/


All Articles