我试图在删除之前检查地址是否未被使用。我的代码如下:
def destroy
@address = current_user.addresses.find_by_id(params[:id])
redirect_to user_addresses_path(current_user) if @address.nil?
if Organisation.find_by_address_id(params[:id]).count == 0 && Event.find_by_address_id(params[:id]).count == 0
@address.destroy
redirect_to user_addresses_path(current_user)
else
flash[:error] = "Cannot delete address because it is being used"
redirect_to user_addresses_path(current_user)
end
end
然而,这给了我一个错误:
undefined method `count' for nil:NilClass
我做错了什么?
答案 0 :(得分:2)
Organisation.find_by_address_id(params[:id])
将返回单个对象,如果不存在nil
的对象,则返回address_id
。
也许你的意思是Organisation.find_all_by_address_id(params[:id])
。