Rails控制台显示视图已呈现,但不会在浏览器中呈现

时间:2014-10-17 12:30:47

标签: javascript ruby-on-rails ajax model-view-controller

这看起来很奇怪。我有一个链接,我想对控制器进行ajax调用以删除用户'响应,然后重定向到另一个页面。这是链接的代码:

<%= link_to 'try again', reset_score_path, remote: true, controller: "pages", 
action: "reset_score", class: "btn btn-primary tryAgain", data: { confirm: 'This 
will reset your score to <strong>zero</strong> and reset all of your answers so you 
can start fresh. Do you want to continue?', commit: "Restart", cancel: "No Thanks",
focus: 'none'}, title: "Try Again?" %>

这是控制器的动作:

def reset_score
  current_user.responses.destroy_all
  current_user.certificate.destroy
  redirect_to action: "course_page1", format: "html" and return
end

但问题是浏览器没有任何反应;它没有重定向。但是控制台显示它正在处理和渲染视图。请参阅控制台输出:

Started GET "/pages/reset_score" for 127.0.0.1 at 2014-10-17 07:19:45 -0500
Processing by PagesController#reset_score as JS
User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 62 ORDER BY "users"."id" ASC LIMIT 1
Response Load (0.3ms)  SELECT "responses".* FROM "responses" WHERE "responses"."user_id" = ?   [["user_id", 62]]
[AWS S3 404 0.306706 0 retries]  head_object(:bucket_name=>"...",:key=>"x.pdf") AWS::S3::Errors::NoSuchKey No Such Key

Redirected to http://localhost:3000/pages/course_page1.html
Completed 302 Found in 315ms (ActiveRecord: 0.6ms)

Started GET "/pages/course_page1.html" for 127.0.0.1 at 2014-10-17 07:19:45 -0500
Processing by PagesController#course_page1 as HTML
User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 62 ORDER BY "users"."id" ASC    LIMIT 1
Rendered pages/course_page1.html.erb within layouts/application (0.3ms)
Rendered layouts/_header.html.erb (0.4ms)
Completed 200 OK in 80ms (Views: 78.5ms | ActiveRecord: 0.2ms)

因此它似乎表明视图已呈现。但是,浏览器实际上并没有显示此视图 - 它只是停留在上一页。

有什么想法吗?我很难过!

(是的,我知道AWS正在提出错误,但我认为它与此问题无关?)

修改: 感谢Pamio的回答,这是控制器的解决方案代码(替换上面的第4行):

def reset_score
    current_user.responses.destroy_all
    current_user.certificate.destroy

    respond_to do |format|
        format.js { render :js => "window.location.href = '#{pages_course_page1_path}'" }
    end
end

2 个答案:

答案 0 :(得分:4)

您使用了redirect_to action: "course_page1", format: "html" and return这是不对的。如果它是一个html请求而不是ajax,重定向将正常工作。因此,如果您想要重定向,尽管请求是ajax,请使用类似这样的

format.js { render :js => "window.location.href = '#{course_page_path}'" }

或者从链接中删除remote: true属性,以便它可以正常工作。

希望有所帮助

答案 1 :(得分:0)

当然,因为你使用的是ajax,而不是标准的调用。如果要重定向,请尝试从remote: true删除link_to。或者如果你想继续使用ajax,你需要通过jQuery从js文件重定向。在您的示例中,它应位于reset_score.js.erb