开发者

Rails RESTful URL's: All Posts under certain Category

开发者 https://www.devze.com 2023-03-01 06:04 出处:网络
Currently I use my posts#index action to show all posts or filter\'em by category in case its specified:

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 :)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消