首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何防止零值导致错误

如何防止零值导致错误
EN

Stack Overflow用户
提问于 2022-08-17 15:08:18
回答 1查看 38关注 0票数 0

我已经创建了一个方法,它在按钮上被调用以更新我的羊群模型下的不同计数。UI计数和NUI计数。见下面的方法

代码语言:javascript
复制
def refresh_ui_and_nui_count
  if params[:herd_id].presence
    herd = Herd.find_by_id(params[:herd_id])
    if herd.nil?
      flash[:error] = t('Unable to find herd')
    else
      herd.set_ui_count
      herd.set_nui_count
    end
  end
  respond_to do |format|
   format.json {render json: {ui_count: herd.ui_count, nui_count: herd.nui_count}, status: :ok}
  end
end 

我增加了一个检查,看看牧群是否为零(第4行),然而,理论上,format.json线也可能失败。在没有herd_id的情况下,我能用什么来防止失败呢?

EN

回答 1

Stack Overflow用户

发布于 2022-08-17 15:45:50

如果没有这样的实体,您可能需要用404错误进行响应。

代码语言:javascript
复制
def refresh_ui_and_nui_count
  herd = Herd.find(params[:herd_id])

  herd.set_ui_count
  herd.set_nui_count

  respond_to do |format|
    format.json { render json: { ui_count: herd.ui_count, nui_count: herd.nui_count }, status: :ok }
  end
end 

在父控制器的某个地方

代码语言:javascript
复制
rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response

def render_not_found_response(exception)
  render json: { error: exception.message }, status: :not_found
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73390862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档