在前面创建的工程中可以发现,routes.rb路由配置中,使用脚手架生成的book的路由配置是这样的:resources :book
:book这样的写法为Symbol,我的理解为 :book写法跟 "book"字符串类似,只是如果我们在很多地方都使用了“book”这个字符串的话,那么将会new出来很多的book字符串,这是不必要的,使用了Symbol类型的 :book会使内存中只存在一份。
那么使用了resouces :book代码之后,ROR会帮我们生成好以下路径
GET | /books | Books | index | display a list of all photos |
GET | /books/new | Books | new | return anHTMLform for creating a new photo |
POST | /books | Books | create | create a new photo |
GET | /books/1 | Books | show | display a specific photo |
GET | /books/1/edit | Books | edit | return anHTMLform for editing a photo |
PUT | /books/1 | Books | update | update a specific photo |
DELETE | /books/1 | Books | destroy | delete a specific photo |
同时生成URL与PATH
books_url 和books_path映射到index和create两个action
new_book_url和new_book_path映射到new action
edit_book_url和edit_book_path映射到edit action
book_url和book_path映射到show, update和destroy三个action
因为路由同时使用HTTP动词和path二者分发请求,因此这七个RESTful路由生成的路径只有4对helper.
如果要在book中添加更多的自定义的路由需要使用member方法,比如在books_controller.rb中添加方法
def test1
render html: "I'm test1 page" << test1_book_url << ";" << test1_book_path
end
则需要在routes.rb中将 resources :book更改成如下:
resources :book do
member do
get 'test1' #本行代码可以写成这样 get :test1
end
end
重启之后访问 http://127.0.0.1:3000/books/1/test1
增加了get 'test1' 之后,会同步生成URL与PATH : test1_book_url 和 test1_book_path
当如果没有太多的member路由规则时,可以用下面的代码进行替换:
resources :books do
get 'test1', on: :member
end
接下来使用稍微复杂的路由,在book_controller.rb中增加方法:
def demo1
render html: "I'm demo1 page" << test3_book_url << ";" << test3_book_path
end
同时更改routes.rb修改为:
resources :book do
member do
get 'test1' #本行代码可以写成这样 get :test1
end
get 'test2', to: 'books#demo1', as: 'test3', on: :member
end
重启之后访问:http://127.0.0.1/books/1/test2
从响应结果中可以观察出 test被路由到了books_controller中的demo1方法中,同时URL于PATH被改变成了test3_book_url于test3_book_path
当如果想限制book的列表页不能被访问到时,可以使用only参数
resources :books, except: [:index]
或者限制只能访问列表页
reources :books, only: [:index] #请同步删除掉index.html.erb中的新增、编辑、删除、查看等跳转