Rails:简单的路由问题
这应该相当容易。我正在学习一个相当过时的视频课程,但我还是想弄清楚这一点:
我创建了一个名为“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
resources
及其单数变体resource
路由说明符实际上同时创建了多个路由,希望能够更轻松地定义应用程序的 URL 呈现方式-明智的。您可以在
rake paths
列表中看到生成的路由。其中每一个都可以使用一系列match
语句手动指定,但通常这不是一种非常有效的方法。使用资源的原因是鼓励遵守标准 REST 约定。
The
resources
and its singular variantresource
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 ofmatch
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.