update_attributes with validations

Posted by Timothy on Stack Overflow See other posts from Stack Overflow or by Timothy
Published on 2010-05-26T14:31:18Z Indexed on 2010/05/26 14:41 UTC
Read the original article Hit count: 169

Filed under:

I have the following contrived example in Rails. I want to make sure the Garage model has at least one car with this.

class Garage
    has_many :cars
    validate :at_least_one_car

    def at_least_one_car
        if cars.count == 0
          errors.add_to_base("needs at least one car")
        end
    end
end

class Car
    belongs_to :garage
end

In my form I have a remove button that will set the hidden field _delete to true for an existing car. Let's say there is only one car object and I "delete" it in my form, if I do garage_object.update_attributes(params[:garage]), it will delete the car model and make the garage object invalid. Is there to a way to make it not update the attributes if it will make the model invalid?

© Stack Overflow or respective owner

Related posts about ruby-on-rails