有没有更好的方法来确保我不删除关系的最后一条记录?我觉得这应该通过验证来完成,但是无法阻止销毁行动。
仅供参考 - 由于嵌套路线
,因此存在@organizationclass 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
答案 0 :(得分:0)
您可能还会考虑before_destroy回调(虽然我认为您的版本不是那么糟糕):
http://edgeguides.rubyonrails.org/active_record_validations_callbacks.html#destroying-an-object