如何redirect_to(:back)两次?

时间:2015-06-04 22:11:49

标签: ruby-on-rails ruby

def update
  if @note.update_attributes(note_params)
    redirect_to :back, notice: "Note was updated."
  else
    render :edit
  end
end

有没有办法重新定向两次?

1 个答案:

答案 0 :(得分:3)

你走了: 这是编辑链接的地方:

<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。在上面的代码中我只是试图解决这个问题而不是真正面向设计模式:)