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

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

最佳答案

干得好:
这是编辑链接的位置:

<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>

提交后,您的url将如下所示:
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 %>

在您有update方法的controller中,在本例中是pages_controller.rb,只需将其返回并重定向用户即可:
 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,并对其进行一些检查所以在视图级别不定义任何变量在上面的代码中,我只是试图解决这个问题,而不是真正的面向设计模式:)

09-30 14:12
查看更多