1

我正在关注 ruby​​onrails.org 上的教程(我假设它是关于 rails 4 的)

在这一行: <%= link_to "My Blog", controller: "posts" %>

rails 如何决定从posts_controller 调用哪个动作?

是否等同于这个? <%= link_to 'My Blog', posts_path %>

如果是这样,什么时候使用哪个?

4

3 回答 3

3

两者<%= link_to "My Blog", controller: "posts" %><%= link_to 'My Blog', posts_path %>是等价的,产生:<a href="/posts">My Blog</a>.

也就是说,第二种<%= link_to 'My Blog', posts_path %>方法是首选方法,因为它是面向资源的。请参阅link_to文档的示例部分。

第一个示例 ,<%= link_to "My Blog", controller: "posts" %>是一种更古老的参数样式,但如果您将非标准操作映射到自定义 url,则与操作结合使用时会证明是有用的。

于 2013-07-12T00:45:41.633 回答
2

index我相信当没有明确提供操作时,路由器默认为操作。

所以是的,在这种情况下,这两个是等价的:

link_to 'My Blog', controller: 'posts'
link_to 'My Blog', posts_path
于 2013-07-12T00:42:32.803 回答
1

实际上,两者都会产生<a>具有href属性的相同标签/posts

<%= link_to 'My Blog', posts_path %>是一个资源丰富的路由,遵循 Rails 定义的 RESTful 约定。posts_path是 的index行动路线posts_controller.rb。此路径很可能由以下资源路由的声明定义posts

# config/routes.rb
resources :posts

# rake db:migrate
              posts GET    /posts(.:format)                        posts#index
                    POST   /posts(.:format)                        posts#create
           new_post GET    /posts/new(.:format)                    posts#new
          edit_post GET    /posts/:id/edit(.:format)               posts#edit
               post GET    /posts/:id(.:format)                    posts#show
                    PUT    /posts/:id(.:format)                    posts#update
                    DELETE /posts/:id(.:format)                    posts#destroy

相反,<%= link_to "My Blog", controller: "posts" %>它不使用命名路由,而是将专门路由到控制器的参数传递。因为 noaction被传递,所以链接助手构建到默认操作的路由 -index操作。鉴于这种路由模式,以下列表近似于上面的命名资源路由:

<%= link_to 'My Blog', controller: 'posts' %> # /posts
<%= link_to 'My Blog', controller: 'posts', action: 'new' %> # /posts/new
<%= link_to 'My Blog', controller: 'posts', action: 'edit', id: post_id %> # /posts/post_id/edit
<%= link_to 'My Blog', controller: 'posts', action: 'show', id: post_id %> # /posts/post_id

首选哪种方法?

在这两种选择之间,最好使用命名posts_path路由。通过使用命名路由,您可以保持代码干燥,并避免与路由更改时链接中断相关的问题,反之亦然。此外,命名路由有助于确保 URL 格式正确,并且链接使用正确的 HTTP 请求方法。

于 2013-07-12T00:56:09.257 回答