这是我遵循的两种方法的完整列表:
1) 默认情况下,redirect_to 将发出 HTTP 302 状态代码。 302 重定向是一种临时更改,将用户和搜索引擎重定向到所需的页面并在有限的时间内将其删除。您可以选择将 301 状态代码指定为 redirect_to。当任何页面被永久移动到另一个位置时,使用 301 状态代码。用户现在将看到新页面,因为它已替换旧页面。这将更改页面在搜索引擎结果中显示时的 URL。
2) redirect_to 将发出一个新的 HTTP 请求,因为它被重定向到不同的控制器操作或 URL。你不应该让浏览器需要重新调用,除非你真的必须这样做,所以当你使用 redirect_to 时总是质疑它是否是正确的,或者渲染会更好。
- redirect_to 将导致跳过当前操作的任何自动模板渲染。
3) 默认情况下,render 会发出一个 HTTP 200 状态码(但如果 ActiveRecord 对象无效,您可能希望将其更改为 422 不可处理实体)。 HTTP 200 OK 成功状态响应码表示请求成功。 422(Unprocessable Entity)状态码表示服务器理解请求实体的内容类型并且请求实体的语法正确但无法处理包含的指令。
4) 渲染将渲染一个模板,并且控制器动作中定义的任何实例变量都将在模板中可用。当然,如果 redirect_to 调用后续操作,实例变量将不可用。重要提示:重定向会命中控制器,而 Render 不会,因此如果您渲染不同的模板,它将不会命中与该模板关联的操作,因此这些实例变量将不可用!
5) 对于渲染,使用 flash.now,而不是普通的 flash。
flash.now[:error] = "There was a problem"
# not
flash[:error] = "There was a problem"
6) 如果您不这样做,则 Flash 消息可能不会显示在呈现的页面上,而是会显示在访问的下一页上。
7) 渲染不会导致当前动作停止执行! redirect_to 不会导致当前动作停止执行!如果您需要绕过操作中代码的进一步执行,则需要调用“return”!在下面的代码中,底部有一个显式渲染,因此您必须执行 return 以避免重定向错误和渲染两者都存在:
def update
@record = Record.new(record_params)
if @record.save
flash[:success] = "record was successfully saved"
redirect_to records_path
return
end
flash.now[:error] = "please fix the problems in the record"
render :edit
end
另一种选择:
def update
@record = Record.new(record_params)
if @record.save
flash[:success] = "record was successfully saved"
redirect_to records_path
else
flash.now[:error] = "please fix the problems in the record"
render :edit
end
end
8) flash 消息提供了一种在动作之间传递临时原始类型(字符串、数组、哈希)的方法。你放在闪光灯里的任何东西都会暴露在下一个动作中,然后被清除。这是发出通知和警报的好方法:
class PostsController < ActionController::Base
def create
# save post
flash[:notice] = "Post successfully created"
redirect_to @post
end
def show
# doesn't need to assign the flash notice to the template, that's done automatically
end
end
show.html.erb
<% if flash[:notice] %>
<div class="notice"><%= flash[:notice] %></div>
<% end %>
由于您可以在 Flash 中同时显示通知和警报,因此您可以这样显示通知和警报:
<% flash.each do |key, value| %>
<%= content_tag :div, value, class: "flash #{key}" %>
<% end %>