Tru*_*oft 1 routing ruby-on-rails
我是ruby-on-rails的初学者,我花了最后一小时尝试做以下事情:
我有一个ruby-on-rails应用程序 - 包含帖子和类别的博客.我希望有另一个帖子的URL(我希望有http://localhost:3000/news而不是http://localhost:3000/posts)首先我试图将控制器和类替换Posts为News,但我放弃了(因为annoyng奇异复数的事情).然后在我的I替换map.resources :posts(案例1)
map.resources :news, :controller => "posts" #case 2
Run Code Online (Sandbox Code Playgroud)
要么
map.resources :posts, :as => 'news' #case 3
Run Code Online (Sandbox Code Playgroud)
在routes.rb我上看到的一些网站.它也不起作用.
我怎样才能做到这一点?
编辑:
输出rake routes是(只有第一行):
对于案例1和3:
posts GET /posts {:action=>"index", :controller=>"posts"}
formatted_posts GET /posts.:format {:action=>"index", :controller=>"posts"}
POST /posts {:action=>"create", :controller=>"posts"}
POST /posts.:format {:action=>"create", :controller=>"posts"}
new_post GET /posts/new {:action=>"new", :controller=>"posts"}
formatted_new_post GET /posts/new.:format {:action=>"new", :controller=>"posts"}
edit_post GET /posts/:id/edit {:action=>"edit", :controller=>"posts"}
formatted_edit_post GET /posts/:id/edit.:format {:action=>"edit", :controller=>"posts"}
post GET /posts/:id {:action=>"show", :controller=>"posts"}
formatted_post GET /posts/:id.:format {:action=>"show", :controller=>"posts"}
PUT /posts/:id {:action=>"update", :controller=>"posts"}
PUT /posts/:id.:format {:action=>"update", :controller=>"posts"}
DELETE /posts/:id {:action=>"destroy", :controller=>"posts"}
DELETE /posts/:id.:format {:action=>"destroy", :controller=>"posts"}
Run Code Online (Sandbox Code Playgroud)
案例2的输出:
news_index GET /news {:action=>"index", :controller=>"posts"}
formatted_news_index GET /news.:format {:action=>"index", :controller=>"posts"}
POST /news {:action=>"create", :controller=>"posts"}
POST /news.:format {:action=>"create", :controller=>"posts"}
new_news GET /news/new {:action=>"new", :controller=>"posts"}
formatted_new_news GET /news/new.:format {:action=>"new", :controller=>"posts"}
edit_news GET /news/:id/edit {:action=>"edit", :controller=>"posts"}
formatted_edit_news GET /news/:id/edit.:format {:action=>"edit", :controller=>"posts"}
news GET /news/:id {:action=>"show", :controller=>"posts"}
formatted_news GET /news/:id.:format {:action=>"show", :controller=>"posts"}
PUT /news/:id {:action=>"update", :controller=>"posts"}
PUT /news/:id.:format {:action=>"update", :controller=>"posts"}
DELETE /news/:id {:action=>"destroy", :controller=>"posts"}
DELETE /news/:id.:format {:action=>"destroy", :controller=>"posts"}
Run Code Online (Sandbox Code Playgroud)
我在案例2中有错误,因为在我的源代码中我没有edit_news,例如<%= link_to 'Edit', edit_post_path(post) %>
"新闻"这个词在单数(成员)和复数(集合)名称之间存在歧义.你可以尝试解决这个问题,但你最终可能会让自己感到困惑,而且还会让你感到困惑.("news_path"应该是成员的id参数,还是收集路径?什么是"新闻"?)
让我们坚持称他们为帖子:
map.resources :posts, :as => "news", :singular => "news"
Run Code Online (Sandbox Code Playgroud)
换句话说,在所有情况下,您都会将资源称为"帖子",但它们会显示在"/ news/*"下的路径中.