Rails用json回复问题

时间:2012-07-12 03:55:30

标签: ruby-on-rails ruby-on-rails-3 json

我正在做一些HTML5上传并遇到一个我似乎无法弄清楚的问题。拿这个功能正常的代码:

if @image.save
    render :json => {:status => "Successfully uploaded image!"}
else
    render :json => {:status => "Something went wrong with your upload!"}
end

这是有效的,它完全符合预期。但是,当我添加respond_to来捕获HTML请求时,它会完全失败(尽管HTML部分可以工作。)

respond_to do |format|
    if @image.save
        format.html {redirect_to(edit_product_path(@image.product), :notice => "Your image was added successfully.")}
        format.json {render :status => "Successfully uploaded image!"}
    else
        format.html {redirect_to(edit_product_path(@image.product), :alert => "An error occurred while attempting to upload your image. Please try again.")}
        format.json {render :status => "Something went wrong with your upload!"}
    end 
end

任何想法都可能出错?我觉得我忽略了一些简单的事情。感谢。

编辑 - 问题已解决

我认为这是一个我不断忽视的蠢事。原来这个请求是HTML,而不是JSON,这是因为由于上传要求内容类型为multipart / form-data,所以respond_to正在触发HTML。

2 个答案:

答案 0 :(得分:2)

渲染需要状态代码,以便以下内容无效

format.json {render :status => "Something went wrong with your upload!"}

你可以把它写成

format.json {render :error => "Something went wrong with your upload!", :status => :bad_request }

答案 1 :(得分:0)

您需要将响应呈现为json

# old
format.json {render :status => "Successfully uploaded image!"}

# new
format.json { render(:json => { :status => "Successfully uploaded image!" }) }