Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove validation with nested attributes

I have a Rails form with nested attributes. User can update its caddy with 2 ways:

  • By writing its delivering address into nested attributes of a model Address,
  • or by selecting a checkbox meaning "I don't want to be delivered"

It's generating a set of params like this :

{
  "id"=>"mine",
  "caddy"=> {
    "address_attributes"=>{"street"=>"", "city"=>"" [...]},
    "use_address"=>"1"
  }
}

Some parts of my models:

Model Caddy < AR::Base
  belongs_to :address
  accepts_nested_attributes_for :address
  attr_accessor :use_address
end

Model Address < AR::Base
  validates :street, :presence => true
end

The issue is that when user check use_address checkbox, the address_attributes should not be used, but they are, and raise a validation error from the street presence.

I tried to add this method into Caddy to override use_addresss= generated by attr_accessor:

def use_address=(v)
  if v == '1'
    self.address_id = nil
    self.address_attributes = {}
    self.address = nil
  end
  super
end

But it changes nothing (address_attributes should be nil then be the hash params).

The only solution I found is to change params directly into my controller, but it's crappy. Do you have any other solution ?

like image 300
pierallard Avatar asked Apr 26 '26 12:04

pierallard


1 Answers

I usually do this with overriding assign_attributes:

def assign_attributes(attrs)
  unless ActiveRecord::ConnectionAdapters::Column.value_to_boolean(attrs.delete(:use_address))
    self.address && self.address.mark_for_destruction
    # or self.address_id = nil if you don't want to destroy existing address
    attrs.delete(:address_attributes)
  end
  super(attrs)    
end
like image 156
BroiSatse Avatar answered Apr 28 '26 04:04

BroiSatse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!