我有简单的博客应用程序,其中包含帖子,评论等,并希望为帖子添加分类,即每个帖子只属于一个类别,并且在帖子中显示。
现在在路线
resources :category do
resources :posts
end
我想要像
这样的路径类别/工作
我生成了CategoryController,但是如何填充它并链接已经存在的帖子控制器?
class CategoryController < ApplicationController
def index
@category = Category.all
end
def show
@category = Category.find(params[:id])
end
end
另外,视图如何看起来像是类别,以便内部显示帖子?
答案 0 :(得分:1)
在您的位置,我会将帖子和类别作为单独的资源。像:
resources :posts
resources :categories, only: [:show]
然后你的路线类别/工作实际上是一个简单的#show动作,你可以像
那样实现class CategoriesController < ApplicationController
def show
@category = Category.find(params[:id])
@posts = @category.posts
end
end
为了让“job”成为Category模型中url的内容,你应该添加类似
的内容class Category < Active
def to_param
name
end
end
通过这种方式,您可以保持资源的清洁和简单,并且不会带来不必要的复杂性。