Rails RESTful URL's: All Posts under certain Category

≡放荡痞女 提交于 2019-12-21 22:20:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!