3-6 routes 解说
root 'topics#index'
这个 route 是用来告诉 rails 你的网站的预设位置是 topics#index
。 topics#index 指的是列出 topics 的那个页面(Topics Controller 的 index action)。
- Rails routes 控制了 URL(网址)如何对应到 server 上的程式码。就好比地址对应到房子或公寓。
config/routes.rb
档像是一个地址簿,列出所有可以使用的地址,以及对应到的程式码。routes.rb
使用了一些简写法,所以我们不会在档案里看到所有的 URL。可以利用终端机来看看有哪些 URL。
在终端机输入 rake routes
。你会看到像这样的东西:
$ rake routes
Prefix Verb URI Pattern Controller#Action
topics GET /topics(.:format) topics#index
POST /topics(.:format) topics#create
new_topic GET /topics/new(.:format) topics#new
edit_topic GET /topics/:id/edit(.:format) topics#edit
topic GET /topics/:id(.:format) topics#show
PATCH /topics/:id(.:format) topics#update
PUT /topics/:id(.:format) topics#update
DELETE /topics/:id(.:format) topics#destroy
root GET / topics#index
这样就可以显示所有你的应用程式会处理的 URL 了。有些冒号(:)开头的是变数, :id 表示资料的 id 编号。括号框起来的是可以省略的。
在 Rails 5 里面,你也可以在开发环境从你的网站上直接看到这个资讯。请打开 http://localhost:3000/rails/info 你就会看到像这样的东西:
如果你随便开一个不存在的网址,也会看到这个画面。(试试看 http://localhost:3000/sandwich)
Exploring Routes (可以跳过)
现在你可以看看你的程式里面可以用的 path 有哪些。我们来试试看我们刚刚产生的一个 topics 的 route。打开 rails console
来玩玩看:
> rails console
2.3.1 :001 > app.topics_path
=> "/topics"
2.3.1 :001 > app.topics_url
=> "http://www.example.com/topics"
app
这个特别的 object 表示你的整个应用程式。 你可以问它有什么 route、玩玩看资料库连线、或是模拟 get
、post
的 web requests(还有很多)。玩过后,记得输入exit
退出。
Updated less than a minute ago