2011-06-29 25 views
3

我正在使用Ruby on Rails 3.0.7,並且在我的應用程序中我有一個Users::Article類(請注意它是名稱空間)。在routes.rb文件中指出如下:更改路由行爲但保留「Convention over Configuration」

resources :users do 
    resources :articles 
end 

我想設置相關Users::Article類的路線,這樣我可以訪問的URL /articles/articles/new/articles/1/articles/1/edit,但我想仍然使用RoR 約定而不是配置「系統」。也就是說,我想用:

  • Users::ArticlesHelper;
  • views/users/articles/<file_name>.html.erb查看文件;
  • 命名路線(<name>_path<name>_url);
  • 和其他 「A LA Ruby on Rails的路」 ......

我怎麼能這樣做?


在幾句話,例如,我想指的是/articles/1路徑,但提出申請準確工作,因爲它正在考慮users/<user_id>/articles/1路徑。

回答

0

這不是一個隱晦的問題,但它與路由參數有關。

您可以使用/articles/:id然後參考控制器內的所有者(用戶)。

第二種情況/users/:user_id/articles/:id會將2個參數傳遞給控制器​​。

0

ActionDispatch::Routing::Mapper::Resources docs

:shallow 

# Generates shallow routes for nested resource(s). When placed on a parent 
# resource, generates shallow routes for all nested resources. 

resources :posts, :shallow => true do 
    resources :comments 
end 

# Is the same as: 
resources :posts do 
    resources :comments, :except => [:show, :edit, :update, :destroy] 
end 
resources :comments, :only => [:show, :edit, :update, :destroy] 

# This allows URLs for resources that otherwise would be deeply nested such as a 
# comment on a blog post like /posts/a-long-permalink/comments/1234 to be 
# shortened to just /comments/1234. 
0

要得到這個>耙路線

users_articles  GET /articles(.:format)   {:action=>"index", :controller=>"users/articles"} 
        POST /articles(.:format)   {:action=>"create", :controller=>"users/articles"} 
new_users_article GET /articles/new(.:format)  {:action=>"new", :controller=>"users/articles"} 
edit_users_article GET /articles/:id/edit(.:format) {:action=>"edit", :controller=>"users/articles"} 
users_article  GET /articles/:id(.:format)  {:action=>"show", :controller=>"users/articles"} 
        PUT /articles/:id(.:format)  {:action=>"update", :controller=>"users/articles"} 
        DELETE /articles/:id(.:format)  {:action=>"destroy", :controller=>"users/articles"} 

我們需要這種在我們的routes.rb

namespace :users, :path => '' do 
    resources :articles 
end 

注:我使用:命名空間,就像你說的那樣。

希望這會有所幫助。