我已经创建了一个方法,它在按钮上被调用以更新我的羊群模型下的不同计数。UI计数和NUI计数。见下面的方法
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的情况下,我能用什么来防止失败呢?
发布于 2022-08-17 15:45:50
如果没有这样的实体,您可能需要用404错误进行响应。
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 在父控制器的某个地方
rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response
def render_not_found_response(exception)
render json: { error: exception.message }, status: :not_found
endhttps://stackoverflow.com/questions/73390862
复制相似问题