Home  >  Q&A  >  body text

ruby - 有一串的ajax操作,其中几个可能会出错,请问怎么样才能优雅的处理

问题描述

现在在一个rails项目中我是想在页面中选中一系列的条目,然后利用ajax向后端传递这一系列条目的id,然后在数据库中更新这些条目中的一些字段内容

下面是我现在的实现代码

@qids = params[:qids]
@qids.each do |id| 
    question = Question.find_by(:id => id, :boxname => "un-matched".to_s)
    if question.nil?
        if Question.find_by(:id => id).update(:boxname => "un-matched".to_s)
        else
            render :json => {:status => "error", :msg => "database error cannot move question to target bucket"}
        end
    else
        render :json => {:status => "error", :msg => "question already exists in this bucket"}
    end
end
render :json => {:status => "ok"}

我现在的话就是在这一系列的更新操作中,假如有一次更新操作出错失败了,就直接返回error给前台了,之后的更新操作也不执行,想问下,如果我想即使有一些出错了,后面的更新操作也还照样执行,但是最后也能返回给前端页面是那几个id对应的条目的更新操作出错失败了,请问各位大大有优雅的解决方案吗?

ringa_leeringa_lee2761 days ago1008

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-04-22 08:57:54

    Make an ajax package for render
    - response.error(msg)
    - response.success()
    - response.warn()
    Omit the json object and call return response.error(msg)
    Doing this can break down part of the if else nesting. I’m not familiar with ruby ​​syntax, just an idea. What do you think?

    reply
    0
  • 怪我咯

    怪我咯2017-04-22 08:57:54

    You can use an array to record the update results of each qid, for example res = [{:qid => 1, :status => "success"}, {:qid => 2, :status => "success"}, {:qid => 3, :status => "fail"}, {:qid => 4, :status => "success"}], and render this res back to the front desk in json format, so that the front desk knows whether each qid has been updated successfully

    reply
    0
  • PHP中文网

    PHP中文网2017-04-22 08:57:54

    Use begin/end, rescue, rasie, ensure to catch and handle exceptions
    After catching the exception, record the current failed id entry and continue with the next cycle

    Finally, just return the recorded failure ID to the front desk

    I believe you can search for the specific grammar through these keywords

    reply
    0
  • Cancelreply