I have a Rails form with nested attributes. User can update its caddy with 2 ways:
Address,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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With