我的博客中包含多个类别的帖子。我想给每个类别一个单独的登录页面,列出该类别中的所有沼泽帖子。
为每个目标网页生成路由和控制器操作的适当方法是什么?它是否会违反REST的精神,在我的帖子控制器中创建多个索引式操作(每个类别一个操作)?如果是这样,我该怎么做呢?
例如,我的博客可能有两个类别,“音乐”和“电影”。
GET /posts/ # would list all posts.
GET /music/ # would list all posts in the "Music" category.
GET /movies/ # would list all posts in the "Movies" category.
道歉,如果这个问题有明显的答案,或者我完全是在问错误的问题。我是Rails和REST的新手,我正在努力了解构建应用程序的最佳方法。
答案 0 :(得分:0)
我不确定它是否完全符合REST精神(我还没有完全理解它),所以我会将这部分问题留给其他人。由于collection
方法存在to extend RESTful routes,我认为只要您不滥用它就允许它。
但是,我不认为拥有没有“/ posts /”前缀的路由是一件好事,因为它会导致“/ music /”路径与一个完全不同的资源相关。
你可以这样做:
(在routes.rb中)
resources :posts do
collection do
get 'music'
get 'movies'
end
end
...然后向控制器添加类似索引的操作,例如:
def music
@posts = Post.where( category: 'music')
render :index
end
如果您有一组有限且常数的类别,可以通过这种方式进行干预:
class Post < ActiveRecord::Base
CATEGORIES = [:music,:movies,:art,:jokes,:friends,:whatever].freeze
end
class PostsController < ApplicationController
Post::CATEGORIES.each do |category|
eval <<-INDEX_LIKE_ACTIONS
def #{category}
@posts = Post.where( category: '#{category}' )
render :index
end
INDEX_LIKE_ACTIONS
end
end
resources :posts do
collection do
Post::CATEGORIES.each {|category| get category.to_s}
end
end