Titan Tang's Blog

Titan Tang's Blog

【转】rails里面reder和redirect_to的区别

render和redirect的区别在于: render 没有执行相对应的controller方法!而redirect_to 则重新执行controller方法,也就是说redirect_to 让浏览器去创建一个新的请求。 render 其参数是有效的,而redirect_to 其参数是重新请求的。 南郭:下面这段代码很有代表性。

def index
  list=Product.find[...];
  render :action => 'list'
end

简单说,其实index这个action跟list的作用是一样的。所以index直接调用list的模板。不需要重新执行list这个action 而redirect_to的话就相当于一个简单的跳转了,会产生一次30X的http指令,这样目标的action会执行。如果上面这个地方换成redirect的话估计list这个action就需要重新在action代码里面获得list了,那么这个index的action应该直接写成

def index
  redirect :action => 'list'
end

但是这样的话,客户端的相应其实是慢了。因为你进到了index以后马上刷新了一下再到了list。而结果也是看到了list结尾的url 不知道说清楚了没有。。。

Comments