Is there a better way to ensure that I don’t delete the last record of a relation? I feel like this should be done through a validation, but could not make that stop the destroy action.
FYI – @organization is present because nested routes
class LocationsController < ApplicationController
....
....
def destroy
@organization = Organization.find(params[:organization_id])
@location = @organization.locations.find(params[:id])
count = Location.find_all_by_organization_id(@location.organization_id).count
if count > 1
@location.destroy
flash[:notice] = "Successfully destroyed location."
redirect_to @organization
else
flash[:notice] = "Could not destroy the only location."
redirect_to @organization
end
end
end
You might also consider the before_destroy callback (though I don’t think your version is all that bad):
http://edgeguides.rubyonrails.org/active_record_validations_callbacks.html#destroying-an-object