【问题标题】:Adding anchors to a URL in Rails在 Rails 中为 URL 添加锚点
【发布时间】:2014-10-20 11:26:32
【问题描述】:

当用户更新失败时,我需要刷新页面。我发现的问题是我不知道如何在页面刷新时向 url 添加片段。下面的代码来自我的 Registrations 控制器,基于 Devise gem。

  def update
    self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
    prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)

    if resource.update_with_password(account_update_params)
      # If the update went well
      if is_navigational_format?
        flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
          :update_needs_confirmation : :updated
        set_flash_message :notice, flash_key
      end

      sign_in resource_name, resource, :bypass => true
      # What's crazy is this works
      respond_with resource, location: edit_user_registration_path(anchor: params["tab_selected"])
    else
      # If the update goes horribly wrong
      clean_up_passwords resource
      #  this is where the problem occurs below
      respond_with resource, location: edit_user_registration_path(anchor: params["tab_selected"])
    end
  end

如您所见,我认为添加位置选项可以解决此问题,但我的 url 仍然返回为 coolsite.com/users,而它应该返回为 coolsite.com/users/#profile。我的问题是如何将片段设置为 URL?

【问题讨论】:

    标签: ruby-on-rails url devise routing


    【解决方案1】:

    我认为问题在于您使用的是respond_with。如果更新成功,则respond_with 将发出redirect_to,它将使用您的:location 选项。

    但是,如果更新不成功,respond_with 只会在edit 模板上调用render,这基本上会忽略:location 选项。不管你放什么路径,它都不会显示在浏览器的地址栏中——你已经向任何映射到update 操作的 URL 发出了请求,它所做的只是提供回复。在这种情况下,location 标头仍会在响应中设置,但基本上什么都不做,因为您使用 200 状态代码进行响应,而不是发出重定向(例如 302 或类似 redirect_to 的任何东西)。

    为了获得锚点,您需要浏览器发出第二个请求(或使用某种 JS 黑客),即您需要像第一种情况一样发出重定向响应。我认为要发生这种情况,您将无法使用respond_with。它还可能导致显示验证错误和记住您在表单中输入的任何先前值的问题(在您的情况下这可能是也可能不是问题)。

    这是respond_with 的主要问题,它模糊了控制器正在做的很多事情,所以你需要很好地理解它是如何工作的。无论如何It's being removed from Rails 4.2 and put into a gem,所以我的建议是开始使用respond_to 和/或基本的渲染/重定向调用。

    【讨论】:

      猜你喜欢
      • 2010-10-22
      • 1970-01-01
      • 2023-03-17
      • 2014-11-14
      • 2012-11-02
      • 1970-01-01
      • 2019-04-22
      • 2015-04-26
      • 1970-01-01
      相关资源
      最近更新 更多