I have a has_many
association that accepts nested attributes. I need for there to be a minimum of 1 associated object in the collection, so I wrote a custom validator:
class MinimumCollectionSizeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if value.size < options[:size]
record.errors[attribute] << (options[:message] || "must have at least #{options[:size]} line.")
end
end
end
The model looks like:
has_many :foos, :dependent=>:destroy
accepts_nested_attributes_for :foos
validates :foos, :minimum_collection_size=>{:size=>1}
This works great on model creation, but fails miserable on update. @my_model.update_attributes(params[:my_model])
returns true even if all the foos are removed by _destroy.
How do I get update_attributes
to behave the same as save
?