问题
Currently I use my posts#index action to show all posts or filter'em by category in case its specified:
PostsController:
def index
@posts = Post.all(:order => "created_at DESC")
@posts = @posts.by_category(params[:category_id]) #Custom named_scope
end
Routes:
map.connect '/post/by_category/:category_id', :controller => :posts, :action => :index
map.resources :users
So /posts will return all the posts, and /posts/by_category/1 will return all posts under category 1
I wonder if there is a way of doing it more RESTful, and maybe to get some pretty url_paths.
I've read the guides (Using latest 2.3 Rails branch) but neither nested routes nor collections seemed appropiate for this case. Thanks :)
回答1:
resources :posts
resources :categories do |categories|
categories.resources :posts
end
Your urls then:
/posts
- all posts
/posts/:id
-certain post
/categories
- all categories
/categories/:id
- certain category
/categories/:id/posts
- all posts within a certain category.
来源:https://stackoverflow.com/questions/5827939/rails-restful-urls-all-posts-under-certain-category