我正在开发一个包含注册,登录和用户可以发布文章的项目。但是我想在文章网址中包含用户的用户名。所以我在 routes.rb
中做到了这一点scope '/:username' do
resources :articles, :path => '/status', only: [:create, :destroy, :show]
end
现在,当我打开显示所有文章的项目索引时,我收到此错误。
No route matches {:action=>"create", :controller=>"articles"} missing required keys: [:username]
我做错了吗?
修改
这是rake routes
Prefix Verb URI Pattern Controller#Action
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
root GET / static_pages#home
help GET /help(.:format) static_pages#help
signup GET /signup(.:format) users#new
login GET /login(.:format) sessions#new
POST /login(.:format) sessions#create
logout DELETE /logout(.:format) sessions#destroy
GET / users#index
POST / users#create
GET /new(.:format) users#new
GET /:id/edit(.:format) users#edit
GET /:id(.:format) users#show
PATCH /:id(.:format) users#update
PUT /:id(.:format) users#update
DELETE /:id(.:format) users#destroy
archings POST /:username/status(.:format) articles#create
arching GET /:username/status/:id(.:format) articles#show
DELETE /:username/status/:id(.:format) articles#destroy
这是routes.rb的代码
Rails.application.routes.draw do
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'signup' => 'users#new'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :users, shallow: true do
resources :articles
end
end
答案 0 :(得分:0)
尽管拥有非常短的网址可能很有吸引力,但您不应该在最低级别使用通配符"您的网址架构 - 除非您的应用程序仅真正处理单一类型的资源。在网址的底层添加通配符会导致巨大的麻烦,因为它会吞下其他所有路径,除非非常小心。
我真的建议您使用/users/:username/articles
。
resources :users, shallow: true do
resources :articles
end
这是一个更好的宁静设计,这意味着您不必将用户名列入应用程序中所需的其他网址(以及将来的网址)的列表。
$ rake routes
的输出:
Prefix Verb URI Pattern Controller#Action
user_articles GET /users/:user_id/articles(.:format) articles#index
POST /users/:user_id/articles(.:format) articles#create
new_user_article GET /users/:user_id/articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy