Rails:简单的路由问题

发布于 2024-11-08 07:49:59 字数 831 浏览 0 评论 0原文

这应该相当容易。我正在学习一个相当过时的视频课程,但我还是想弄清楚这一点:

我创建了一个名为“Say”的控制器,它又创建了一个 say_controller.rb。在里面,我创建了一个名为“hello”的新方法,因此 say_controller 的内部如下所示:

class SayController < ApplicationController
    def hello
        respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @derps }
        end
    end

end

然后,我在 /app/view/say/ 下创建了一个 hello.html.erb,其中包含一些 html。如果您尝试通过 localhost:3000/say/hello 访问它,则会出现路由错误。所以我将其添加到routes.rb中:

match 'say/hello' => 'say#hello'

不过,这就是问题 - 如果您运行rails生成脚手架Derp,那么在路线中您将看到

resources:derps

,这是唯一会在那里的东西。如果没有特定的匹配命令,Rails 如何知道路由到它?即我有点明白这里发生了什么,但我想了解这个理论。 更重要的是,我将来在手动创建视图和控制器时需要依赖什么(我什至必须这样做吗?) - Rails 中为每个视图和控制器手动添加一行到 paths.rb 是标准程序吗?视图/控制器?

谢谢:)

This should be fairly easy. I'm following along with a fairly outdated video course as it seems like but I'd like to figure this out nonetheless:

I created a controller called "Say," which in turn created a say_controller.rb. Inside there, I created a new method called 'hello,' so the inside of say_controller looks like this:

class SayController < ApplicationController
    def hello
        respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @derps }
        end
    end

end

Then, I created a hello.html.erb under /app/view/say/ with some html in it. If you try to access it at localhost:3000/say/hello, there's a routing error. So I added this to routes.rb:

match 'say/hello' => 'say#hello'

Here's the question though - if you run rails generate scaffold Derp, then in routes you'll see

resources:derps

and that's the only thing that's gonna be there. How does Rails know to route to it without a specific match command? ie I kinda see what's happening here but I'd like to understand the theory.
More importantly, what do I need to rely on in the future when creating views and controllers by hand (will I even have to do that?) - is it standard procedure in Rails to add a line to routes.rb manually for each and every view/controller?

Merci :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

总以为 2024-11-15 07:49:59

resources 及其单数变体 resource 路由说明符实际上同时创建了多个路由,希望能够更轻松地定义应用程序的 URL 呈现方式-明智的。

您可以在rake paths列表中看到生成的路由。其中每一个都可以使用一系列 match 语句手动指定,但通常这不是一种非常有效的方法。

使用资源的原因是鼓励遵守标准 REST 约定。

The resources and its singular variant resource routing specifiers actually create a number of routes at the same time in the hopes of making it a lot easier to define how your application is presented URL-wise.

You can see the generated routes in the rake routes listing. Each of these could be specified manually with a series of match statements, but generally that's not a very effective way to do it.

The reason for using resources is to encourage conforming to standard REST conventions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文