【问题标题】:How to redirect_to(:back) two times?如何重定向_to(:back) 两次?
【发布时间】:2015-08-19 17:29:12
【问题描述】:
def update
  if @note.update_attributes(note_params)
    redirect_to :back, notice: "Note was updated."
  else
    render :edit
  end
end

有没有办法重定向回来两次?

【问题讨论】:

  • 你怎么知道他们在两次点击前是从哪里来的?
  • these answers有什么有用的吗?
  • 它们来自@Makoto 的四个显示页面之一,因为注释是多态的,因此当他们单击编辑注释然后单击更新时,它们将被重定向回注释编辑表单,但我希望它们重定向回如果可能的话到显示页面:)
  • 不,@Kimball 他们没有解决返回两次但感谢您的尝试
  • 不能将引用页面保存在会话状态吗?即使您最终在 4 个(或更多!)位置复制代码,它似乎也不太可能困扰您而不是返回两次。如果用户在同一个会话中打开了多个选项卡怎么办?正如@Makoto 暗示的那样,无法知道“两次后退”在哪里。

标签: ruby-on-rails ruby


【解决方案1】:

给你: 这是编辑链接所在的位置:

<p id="notice"><%= notice %></p>
<% url = "#{request.protocol}#{request.host_with_port}#{request.fullpath}" %>
<%= link_to 'Create New Page and Return Here', edit_page_path(1, :url => Base64.encode64(url) ) %>
<br>

提交后,您的网址将是这样的: http://localhost:3000/pages/1/edit?url=aHR0cDovL2xvY2FsaG9zdDozMDAwL2R1bW1pZXM%3D%0A

在编辑表单中: 我称之为 pages/_form.html.erb,将 URL 作为隐藏参数传递。

<%= form_for(@page) do |f| %>
  <% if @page.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@page.errors.count, "error") %> prohibited this page from being saved:</h2>    
      <ul>
      <% @page.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>    
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :permalink %><br>
    <%= f.text_field :permalink %>
  </div>
    <%= hidden_field_tag :url, params[:url].to_s %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

在您有更新方法的控制器中,在本例中为 pages_controller.rb,只需 Base64 将其返回并重定向用户:

 def update
    redirection = nil
    if params[:url].present?
      redirection = Base64.decode64(params[:url].to_s)
    end
    if @page.update(page_params)

      if redirection.present?
        path = redirection
      else
        path = @page
      end
      redirect_to path, notice:  'All Done.'
    else
      render :edit
    end
  end

现在用户更新表单并重定向回第一个显示或索引页面或她来自的任何页面。

希望对您有所帮助。 PS:您可能需要稍微清理一下并从控制器传递 url,并对其进行一些检查。因此,您无需在视图级别定义任何 var。在上面的代码中,我只是试图解决这个问题,而不是真正面向设计模式:)

【讨论】:

  • 别担心,伙计。很高兴我能帮助你。干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 1970-01-01
  • 2013-11-20
  • 2016-09-03
  • 1970-01-01
  • 2021-01-25
  • 2014-02-26
相关资源
最近更新 更多