【问题标题】:Change redirect_to format to :js in Rails在 Rails 中将 redirect_to 格式更改为 :js
【发布时间】:2013-09-02 13:52:08
【问题描述】:

我有一个控制器操作,只能由已登录的用户访问。如果用户未登录,我想将他们重定向到登录表单,这是一个 ajax 驱动的灯箱。虽然初始请求是html 格式,但我需要更改为js。现在,我正在尝试这样:

def new
  if user_signed_in?
    @company = Company.new
  else
    redirect_to new_user_session_path, format: 'js'
  end
end

不幸的是,它仍然将重定向视为html 格式。有没有办法让重定向被视为js

【问题讨论】:

  • 你试过之前的过滤器吗? guides.rubyonrails.org/action_controller_overview.html
  • 感谢您的提示!这大大清理了我的代码,但它并没有解决我遇到的主要问题,即将格式从html 更改为js。如果对此有更多提示,请告诉我。
  • 我认为您可能必须将它们重定向到一个页面,然后触发 light osx box modal。
  • @simonmorley 这是我最终使用的方法。

标签: ruby-on-rails ajax redirect format


【解决方案1】:

我在 rails 3.2.13 中尝试过这个,它的作品,我希望它可以解决

if user_signed_in?
  .....
else
  if request.xhr?
    flash[:notice] = "Please login."
    flash.keep(:notice)
    render :js => "window.location = #{new_user_session_path}"
  else
    .....
  end
end

【讨论】:

  • 不幸的是,在 4.0 中这不起作用。 js 仍然呈现为html,所以我得到的只是一个带有文本render :js => "window.location = #{new_user_session_path}" 的未格式化页面。不过还是谢谢。
【解决方案2】:

我认为您可能正在寻找一个 respond_to 块以及前面提到的过滤器:

class CompaniesController < ApplicationController
  before_filter :login

  def new 
    @company = Company.new

    render json: @company, layout: false # layout false if you do not want rails to render a page of json
  end

  private

  def login
    if !user_signed_in?
     #your login code here
    end
  end
end

别忘了将你的 dataType ajax 选项设置为 json:

$.ajax({
    url: "company/new" //your rails url, what is there is just my best guess
    data: query, //whatever paramaters you have
    dataType: "json", // or html, whichever you desire
    type: "GET",
    success: function (data) {
        //your code here
    }
 });

【讨论】:

  • 感谢您的回复。不幸的是,问题是“新公司”的链接不是remote: true,所以我发送的是html 格式的请求,而不是js。不知何故,我需要告诉 Rails 以 js 的形式返回请求。
  • 如果您只想从此控制器方法返回 json,您所要做的就是渲染 json:@company,layout:false。我编辑了答案以包含此代码。
  • 不幸的是,这不起作用。也许 Rails 4 发生了一些变化?
【解决方案3】:

对于任何来到这里并使用 Rails 5 的人我都这样做了,如果有人在想要重定向时在控制器 youractionname 函数中设置@redirect 变量,这将在 youractionname.js.erb 文件中工作。

# ruby control flow
<% if @redirect != nil %>
  // javascript call to use rails variable as redirect destination.
  location.replace("<%=@redirect%>");
<% end %>

【讨论】:

    猜你喜欢
    • 2013-09-08
    • 2013-02-24
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    相关资源
    最近更新 更多