Ruby-on-rails link_to、redirect_to 和 render 之间有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17236122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what is the difference between link_to, redirect_to, and render?
提问by Sami
I am confused about the main difference(s) among link_to, redirect_toand renderin Rails. anyone can please explain.
我感到困惑之间的主要区别(S) link_to,redirect_to并render在轨道上。任何人都可以请解释。
回答by RedXVII
link_to is used in your view, and generates html code for a link
link_to 在您的视图中使用,并为链接生成 html 代码
<%= link_to "Google", "http://google.com" %>
This will generate in your view the following html
这将在您的视图中生成以下 html
<a href="http://google.com">Google</a>
redirect_to and render are used in your controller to reply to a request. redirect_to will simply redirect the request to a new URL, if in your controller you add
redirect_to 和 render 在您的控制器中用于回复请求。redirect_to 只会将请求重定向到新的 URL,如果在您的控制器中添加
redirect_to "http://google.com"
anyone accessing your page will effectively be redirected to Google
任何访问您页面的人都会被有效地重定向到 Google
render can be used in many ways, but it's mainly used to render your html views.
render 可以以多种方式使用,但它主要用于呈现您的 html 视图。
render "article/show"
This will render the view "app/views/article/show.html.erb"
这将呈现视图“app/views/article/show.html.erb”
The following link will explain the redirect_to and the render methods more in detail http://guides.rubyonrails.org/layouts_and_rendering.html
以下链接将更详细地解释 redirect_to 和渲染方法 http://guides.rubyonrails.org/layouts_and_rendering.html
回答by sargas
From the Documentation:
从文档:
Regarding rendering a view vs redirecting a request
关于呈现视图与重定向请求
. . . render tells Rails which view (or other asset) to use in constructing a response. The redirect_to method does something completely different: it tells the browser to send a new request for a different URL.
. . . render 告诉 Rails 在构建响应时使用哪个视图(或其他资产)。redirect_to 方法做一些完全不同的事情:它告诉浏览器向不同的 URL 发送一个新请求。
Regarding rendering a view
关于渲染视图
. . . render :action doesn't run any code in the target action . . .
. . . render :action 不会在目标 action 中运行任何代码。. .
Regarding redirecting a request
关于重定向请求
. . . Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code.
. . . 您的代码停止运行并等待浏览器的新请求。碰巧您已经通过发回 HTTP 302 状态代码告诉浏览器它接下来应该发出什么请求。
Basically:
基本上:
link_tois a helper method to generate URLs usually used in your views (.html.erbfiles)
link_to是一种生成 URL 的辅助方法,通常在您的视图中使用(.html.erb文件)
rendertells your controller to render a view without passing any data (say, from a form) to the next controller action.
render告诉您的控制器渲染视图而不将任何数据(例如,从表单)传递给下一个控制器操作。
redirect_todoes a 302 page redirect, passing data (say, from a form) to either a controller action on your web app, or an external app (ex: google, facebook, a web article you liked, etc)
redirect_to执行 302 页面重定向,将数据(例如,从表单)传递到您的网络应用程序上的控制器操作或外部应用程序(例如:google、facebook、您喜欢的网络文章等)
回答by Ryan Lue
I actually just wrote a blog post about this. The most important bits are copied below (with modifications).
我实际上只是写了一篇关于这个的博客文章。下面复制了最重要的位(经过修改)。
Controller Methods: rendervs. redirect_to
控制器方法:rendervs。redirect_to
renderand redirect_toare the two ways that controller actions end (generally speaking). To understand how they work, let's review what controllers do in a Rails app:
render并且redirect_to是控制器动作结束的两种方式(一般来说)。要了解它们是如何工作的,让我们回顾一下控制器在 Rails 应用程序中的作用:
- A user tries to access a page.
(http://localhost:3000/books/index.html) - Under the hood, the browser sends an HTTP request for the specified path on the server.
(GET /books/index.html) - The Rails routing system then looks up which controller corresponds to the given request path.
(books GET /books/index(.:format) books#index) - The controller prepares some data and then tells the server what response (i.e.,what HTTP header/body content) to send back to the client.
- 用户尝试访问页面。
( http://localhost:3000/books/index.html) - 在幕后,浏览器向服务器上的指定路径发送 HTTP 请求。
(GET /books/index.html) - Rails 路由系统然后查找对应于给定请求路径的控制器。
(books GET /books/index(.:format) books#index) - 控制器准备一些数据,然后告诉服务器什么响应(即什么 HTTP 标头/正文内容)要发送回客户端。
This last step occurs explicitly when you call renderor redirect_to, or implicitly if you leave it out.
这最后一步在您调用renderor时显式发生redirect_to,或者如果您省略它则隐式发生。
That is,
那是,
def index
@books = Book.all
end
is the same as
是相同的
def index
@books = Book.all
render :index
end
render :indexsays, ‘combine the data I've prepared (@books = Book.all) with the books/index.html.erbview template to generate a complete HTML document, then send that back to the client.'
render :index说,“将我准备的数据 ( @books = Book.all) 与books/index.html.erb视图模板结合以生成完整的 HTML 文档,然后将其发送回客户端。”
redirect_to @booksays, ‘tell the client to start the whole process over again, issuing a new GETrequest to url_for(@book).
redirect_to @book说,'告诉客户端重新开始整个过程,向 发出新GET请求url_for(@book)。
If you omit both, the action will render a template with the same name as the action itself. In other words, you only need to call renderexplicitly when the view template you want doesn't match the action you're rendering it from.
如果两者都省略,动作将呈现与动作本身同名的模板。换句话说,您只需要在render您想要的视图模板与您从中呈现它的操作不匹配时显式调用。
Note that not every controller action has a corresponding view template. Generally, #create, #update, and #destroy(which are all routed to non-GETHTTP requests) attempt to make some change to the database and then either redirect_tosome resource (if it succeeded) or re-renderthe form that preceded it, along with any errors (if it failed).
请注意,并非每个控制器操作都有相应的视图模板。通常,#create, #update, 和#destroy(都被路由到非GETHTTP 请求)尝试对数据库进行一些更改,然后尝试对redirect_to某些资源(如果成功)或重新更改render之前的表单,以及任何错误(如果它失败的)。
As the official guides explain(emphasis mine),
正如官方指南所解释的(强调我的),
These two methods [
renderandredirect_to] represent the two basic action archetypes used in Action Controllers: Get-and-showand do-and-redirect. Most actions are variations on these themes.
这两个方法 [
render和redirect_to] 代表了 Action Controller 中使用的两个基本动作原型:Get-and-show和do-and-redirect。大多数行动都是这些主题的变体。
View Methods: rendervs. link_to
查看方法:render对比link_to
renderis also used within view templates themselves. Rather than generating a complete HTML document, it's used to insert a partial view templateinto a larger one. Here's the upshot:
render也用于视图模板本身。它不是生成完整的 HTML 文档,而是用于将部分视图模板插入到更大的模板中。结果如下:
- You can create partial view templatefiles to be inserted into your standard templates (think of them as modular page components).
- Filenames of partials must begin with an underscore (e.g.,
_nav.html.erb). - Use
render 'nav'if you want to include the_nav.html.erbpartial from a view located in the same folder. - Use
render 'shared/nav'if you want to include the partial atapp/views/shared/_nav.html.erbfrom any view in your project. - Various options and shorthand syntaxes exist for passing data into a partial, rendering multiple partials from a collection object, and more. See the guidesfor details.
- 您可以创建要插入到标准模板中的部分视图模板文件(将它们视为模块化页面组件)。
- 部分文件名必须以下划线开头(例如,
_nav.html.erb)。 render 'nav'如果要包含位于同一文件夹中的视图中的_nav.html.erb部分,请使用。- 使用
render 'shared/nav',如果你想包括部分在app/views/shared/_nav.html.erb从项目中的任何看法。 - 存在各种选项和速记语法,用于将数据传递到局部、从集合对象渲染多个局部等等。有关详细信息,请参阅指南。
link_tois just a convenience method for inserting anchor tags (a hreftags) into your view templates. This is useful because a lot of the URLs you'll want to link to are other pages within your application, and those URLs can be referenced using objects or "helper methods", like so:
link_to只是一种将锚标记(a href标签)插入到您的视图模板中的便捷方法。这很有用,因为您要链接到的许多 URL 是应用程序中的其他页面,并且可以使用对象或“辅助方法”引用这些 URL,如下所示:
= link_to 'Back', books_path # renders as <a href="/books">Back</a>
= link_to 'View', @book # renders as <a href="/book/1">View</a> or similar
回答by Mike Yockey
link_tois for use in ERB templates. It outputs a link to a specific path or url.
link_to用于 ERB 模板。它输出指向特定路径或 url 的链接。
redirect_tois for use in controllers. It causes the client to request the specified path or url once the controller method exits.
redirect_to用于控制器。一旦控制器方法退出,它会导致客户端请求指定的路径或 url。
renderis also for use in controllers. It causes Rails to render the specified template.
render也用于控制器。它使 Rails 呈现指定的模板。
redirect_toand rendermay only be called once in a given controller method.
redirect_to并且render只能在给定的控制器方法中调用一次。
回答by Kyri Elia
A link_tois used on a form within rails, and is a helper to create a link element within html. The other two are not used in forms, but rather are used in controllers.
Alink_to用于 rails 中的表单,并且是在 html 中创建链接元素的助手。另外两个不在表单中使用,而是在控制器中使用。
You rendera page if your controller method is linked to that page. E.g. calling 'new' should render the 'new item' page. They fulfil the request that has just been made.
您render若你的控制器方法被链接到页面的页面。例如,调用“new”应该呈现“new item”页面。他们满足了刚刚提出的要求。
redirectis used for exactly that - redirecting. For example, if you try accessing a page where you have to be logged in, you redirect the user to the login page. So, redirects basically spawn a new request.
redirect正是用于那个 - 重定向。例如,如果您尝试访问必须登录的页面,您会将用户重定向到登录页面。所以,重定向基本上会产生一个新的请求。
回答by Nathaniel Johnson
link_to will output a standard html anchor=a link (link_to documentation)
link_to 将输出一个标准的 html anchor=a 链接(link_to 文档)
redirect_to is commonly used for page responses such as update and delete. It will take the parameters you give it and will direct your page appropriately.
(redirect_to documentation)
redirect_to 通常用于页面响应,例如更新和删除。它将采用您提供的参数,并将适当地引导您的页面。
(redirect_to 文档)
render is used for loading partials or loading specific .erb files into others. (render documentation)
There are a bunch of examples on thisrails guide which should explain render and redirect_to. link_to is pretty different from rendering and redirect_to
render 用于加载部分文件或将特定的 .erb 文件加载到其他文件中。(渲染文档)
在这个Rails 指南上有很多例子可以解释 render 和 redirect_to。link_to 与渲染和重定向非常不同
回答by stonefruit
A link_to creates a hyperlink to a specific URL, which appears on the HTML.
link_to 创建指向特定 URL 的超链接,该超链接出现在 HTML 中。
A redirect_to will decide where to link you to, depending on certain options. For example, if someone is logged on as a user, you might want to show him his settings page, else redirect_to the home page.
redirect_to 将决定将您链接到何处,具体取决于某些选项。例如,如果有人以用户身份登录,您可能希望向他显示他的设置页面,否则重定向_到主页。
A render will open the rendered file, take its content and paste it into the existing file, before sending the whole chunk to the recipient.
渲染将打开渲染的文件,获取其内容并将其粘贴到现有文件中,然后将整个块发送给接收者。
Hope I am right.
希望我是对的。
回答by Agis
From the official Rails guides:
来自官方Rails 指南:
As you've seen, render tells Rails which view (or other asset) to use in constructing a response. The redirect_to method does something completely different: it tells the browser to send a new request for a different URL.
如您所见,render 告诉 Rails 在构建响应时使用哪个视图(或其他资产)。redirect_to 方法做一些完全不同的事情:它告诉浏览器向不同的 URL 发送一个新请求。

