我是ruby-on-rails的初学者,我花了最后一小时尝试做以下事情:
我有一个ruby-on-rails应用程序 - 包含帖子和类别的博客。
我想为帖子添加其他网址(我希望http://localhost:3000/news
代替http://localhost:3000/posts
)首先,我尝试将控制器和类从Posts
替换为News
,但我放弃了(因为annoyng奇异复数的东西)。然后我在我的map.resources :posts
(案例1)替换为
map.resources :news, :controller => "posts" #case 2
或
map.resources :posts, :as => 'news' #case 3
正如我在some websites看到的routes.rb
中的。它也不起作用。
我该怎么做?
编辑:
rake routes
的输出是(仅第一行):
:
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"}
案例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"}
我在案例2中遇到错误,因为在我的源代码中我没有edit_news
,例如我有<%= link_to 'Edit', edit_post_path(post) %>
答案 0 :(得分:6)
“新闻”一词在单数(成员)和复数(集合)名称之间存在歧义。你可以尝试解决这个问题,但你最终可能会让自己感到困惑,而且还会让你感到困惑。 (“news_path”应该是成员的id参数,还是收集路径?什么是“新闻”?)
让我们坚持称他们为帖子:
map.resources :posts, :as => "news", :singular => "news"
换句话说,在所有情况下,您都会将资源称为“帖子”,但它们会显示在“/ news /*”下的路线中。
答案 1 :(得分:0)
您的第一步很好:将所有Post * s类替换为News *类。调用你的模型新闻和控制器NewsController应该不是问题。确保您在代码中找到所有匹配项(post_path
之类的内容也应替换为news_path
)。
接下来,修改您的路线
map.resources :news
为了使用NewsController而不是PostsController。它应该工作。
注意:不要忘记重新启动您的网络服务器。