美文网首页
render 和 redirect_to 的区别

render 和 redirect_to 的区别

作者: 吃果果的蛐蛐 | 来源:发表于2018-10-15 21:40 被阅读0次

执行到 redirect_to 方法时,代码会停止运行,等待浏览器发起新请求。你需要告诉浏览器下一个请求是什么,并返回 302 状态码。

下面通过实例说明。

def index
  @books = Book.all
end
 
def show
  @book = Book.find_by(id: params[:id])
  if @book.nil?
    render action: "index"
  end
end

在这段代码中,如果 @book 变量的值为 nil,很可能会出问题。记住,render :action 不会执行目标动作中的任何代码(即controller中对应的action代码),因此不会创建 index 视图所需的 @books 变量。修正方法之一是不渲染,而是重定向:

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

这种方法唯有一个缺点:增加了浏览器的工作量。
在小型应用中,额外增加的时间不是个问题。如果响应时间很重要,这个问题就值得关注了。下面举个虚拟的例子演示如何解决这个问题:

def index
  @books = Book.all
end
 
def show
  @book = Book.find_by(id: params[:id])
  if @book.nil?
    @books = Book.all
    flash.now[:alert] = "Your book was not found"
    render "index"
  end
end

在这段代码中,如果指定 ID 的图书不存在,会从模型中取出所有图书,赋值给 @books 实例变量,然后直接渲染 index.html.erb 模板,并显示一个闪现消息,告知用户出了什么问题。

参考https://ruby-china.github.io/rails-guides/layouts_and_rendering.html#using-render

相关文章

  • render 和 redirect_to 的区别

    执行到 redirect_to 方法时,代码会停止运行,等待浏览器发起新请求。你需要告诉浏览器下一个请求是什么,并...

  • render和redirect_to

    在controller,model和views中都可以使用render <%= render @users %>会...

  • Rails render 和 redirect_to 进阶理解

    该篇文章在个人博客中也可查阅:Rails render 和 redirect_to 进阶理解 基本用法 不同的跳转...

  • Rails布局和视图渲染

    创建响应 从控制器的角度,创建HTTP响应有三种方法: 调用 render 方法 调用 redirect_to 方...

  • render_to_response 和 render区别(转载

    转载地址:https://www.douban.com/note/278152737/ 自django1.3开始:...

  • shortcart

    render和render_to_response之间的区别是是否传入request到模板中 更好用的是提供的通用...

  • app.render()、res.render()的区别

    您可以在根级别调用app.render,并且只能在路由/中间件中调用res.render。app.render总是...

  • 玩转Vue_render函数

    新创建一个html,利用之前学过的组件注册完成渲染 使用render函数也可以渲染组件 区别 : 使用render...

  • 2019-07-03render函数

    新创建一个html,利用之前学过的组件注册完成渲染 使用render函数也可以渲染组件 区别 : 使用render...

  • render函数

    使用render函数可以渲染组件 区别 : 使用render渲染的组件会完全替换el挂载元素中的内容,而第一种方法...

网友评论

      本文标题:render 和 redirect_to 的区别

      本文链接:https://www.haomeiwen.com/subject/ldpfzftx.html