【问题标题】:Rails 3: redirect_to with :remote => trueRails 3:redirect_to with :remote => true
【发布时间】:2012-10-30 20:26:23
【问题描述】:

我有一个远程调用的删除链接:

<%= link_to image_tag("trash.png"), [current_user, bookcase], method:  :delete, :remote => true, confirm: "You sure?", title:   bookcase.image %>

在我的控制器中,我通过重定向结束删除功能:

def destroy
  @bookcase.destroy
  redirect_to current_user
end

这可行,只是它将用户重定向到“user/show.html.erb”文件而不是“user/show.js.erb”文件。如何重定向用户,指定使用哪种格式?

【问题讨论】:

  • 应该是render而不是redirect_to,ajax请求不能重定向。我认为发送到服务器的请求不是ajax请求,而是delete(post)请求
  • 是否可以远程发送删除[post]请求?
  • 点击删除链接后能否查看服务器日志并告诉我传入的请求是xhr还是post
  • 这是一个 DELETE 请求,它正在通过 JS 处理。不过,我找到了另一种可行的解决方案。我没有重定向,而是创建了一个 destroy.js.erb 文件,该文件呈现由“users/show.html.erb”呈现的相同部分。这很有效,尽管也许有更优雅的解决方案?
  • 那么下面的答案是错误的。澄清并发布您自己的答案

标签: ajax ruby-on-rails-3 redirect


【解决方案1】:

不知道这是否回答了这个特定问题,但有些人可能会发现以下内容有帮助:

module AjaxHelper
  def ajax_redirect_to(redirect_uri)
    { js: "window.location.replace('#{redirect_uri}');" }
  end
end

class SomeController < ApplicationController
  include AjaxHelper

  def some_action
    respond_to do |format|
      format.js { render ajax_redirect_to(some_path) }
    end
  end
end

【讨论】:

    【解决方案2】:

    我很确定您可以像这样在 redirect_to 中指定格式

    redirect_to current_user, format: 'js'

    【讨论】:

    • 你的答案是对的,而且看起来 rails 在使用 :remote => true 时会默认使用 js。我遇到了这个问题,因为我实际上对 AJAX 采取了稍微不同的方法。尽管它有一些缺点,但我已经继续并更改了我的代码以在这种情况下使用更传统的 :remote => true 。谢谢!
    • 您可以随时将 dataType 添加到您的 ajax,这样您就可以完全控制您的 ajax 而不是使用 Rails 远程:true
    • 应该是render而不是redirect_to,ajax请求不能重定向。我觉得发给服务器的请求不是ajax请求,而是delete(post)请求
    【解决方案3】:

    我很确定这段代码会起作用。

    render :js => "window.location = '/jobs/index'
    

    你可以在action /controller_name/action name/中使用这段代码

    【讨论】:

      【解决方案4】:

      我尝试了接受的答案,但对我不起作用(RAILS 6),对我有用的是:

      format.js { redirect_to current_user }
      

      希望这对某人有所帮助

      【讨论】:

        猜你喜欢
        • 2012-07-03
        • 2018-02-26
        • 2016-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-27
        • 2023-03-20
        相关资源
        最近更新 更多