Rails 请问 render 和 redirct_to 的主要区别

Sunnyroger · 2012年11月01日 · 最后由 zengfengbo 回复于 2016年12月12日 · 6264 次阅读

看 rails guides,不太懂

def index
  @books = Book.all
end

def show
  @book = Book.find_by_id(params[:id])
  if @book.nil?
    redirect_to :action => :index
  end
end

把代码中的 redirct_to 换成 render 会怎样 为什么改成 render "index", :alert => 'Your book was not found!' 就是比较好的代码

一个是渲染模板,一个是跳转到另一个网址,两者根本就没有共同点

#1 楼 @gaicitadie 那 guides 上的那段解释说 render 只是渲染模版不运行任何代码,那上面的那段代码应该使用的是 redirct_to,为什么后面改成了说 render "index", :alert => 'Your book was not found!'就是比较好的代码

redirect_to :action => :index需要跳转到 index 这个 action,然后渲染 index.html.erb,额外增加了一次 http 请求。直接render "index", :alert => 'Your book was not found!'就把额外的这次请求给免了

匿名 #4 2012年11月01日

@Sunnyroger 这里用 render 的前提是先声明@books = Book.all,这样相比用redirect_to的响应要快些,因为它不用跳转页面。ROR 新手的理解。:D

redirect_to 是重新向服务器提交一次 request 请求,而 render 就是直接渲染一个页面,然后 response,要是理解 http 请求的话,这个就非常好理解了。

#4 楼 @rorhaha 对的,的确需要提前声明@books=Book.all,这个声明是为什么呢

匿名 #7 2012年11月02日

#6 楼 @Sunnyroger 你可以看到 show 方法只定义了@book,当@book.nil?为 true 时会渲染 index.html.erb 模板,这个模板里面有用到@books, 而 render 并不会执行 index 方法里的任何代码,所以就得在 show 方法里面额外定义@books好传给 views 了。

render 是服务器直接给你页面。 redirect_to 是服务器给浏览器地址,浏览器再次请求服务器给自己的哪个地址,跳转。

你的例子中,如果改成 render,那么就是服务器直接给你呈现 index,但是使用的是 show 的上下文,index view 所需要的参数可能就是空的,逻辑可能会出问题,自己试一试,然后看看日志,就会明白了。

我明白了: render 是渲染模板 redirect_to 是跳转,也就是发送新的请求到某 Action

#2 楼 @Sunnyroger #10 楼 @dingjop

去某窗口办材料,说完请求后

办事员 render:准备好你的材料后交给你 办事员 redirect: 交给你一张纸条上面写”请去 5 号窗口办理“

#11 楼 @knwang 这才是理解透彻的答案啊 不愧是搞 ror 教学的 thumb up

需要 登录 后方可回复, 如果你还没有账号请 注册新账号