确保至少有一条相关记录仍然存在

时间:2011-02-15 00:36:32

标签: ruby-on-rails-3

有没有更好的方法来确保我不删除关系的最后一条记录?我觉得这应该通过验证来完成,但是无法阻止销毁行动。

仅供参考 - 由于嵌套路线

,因此存在@organization
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

1 个答案:

答案 0 :(得分:0)

您可能还会考虑before_destroy回调(虽然我认为您的版本不是那么糟糕):

http://edgeguides.rubyonrails.org/active_record_validations_callbacks.html#destroying-an-object

相关问题