列出某个类别的所有帖子
Listing all posts from a certain category
我目前有一个 posts 模型,其中有一个 category:string 列。我希望显示某些类别中的所有帖子。
例如单击 'Technology' 类别 link - 加载所有类别为 apple 的帖子。
在堆栈溢出上找不到任何东西,但我可能找错了东西。任何帮助将不胜感激!
谢谢
Post.where(category: 'Animals')
将 return 所有具有指定类别的 post。
关于问题下的评论 - 是的,您可以从额外的模型中受益 Category
,因为 post 可以有多个类别。
您可以将关系定义为以下之一:
HBTM
has_and_belongs_to_many :categories # post.rb
has_and_belongs_to_many :posts # category.rb
has_many到
post.rb
has_many :categories_posts
has_many :categories, through: :categories_posts
category.rb
has_many :categories_posts
has_many :posts, through: :categories_posts
categories_posts.rb
belongs_to :category
belongs_to :post
编辑
要将选择类别添加到表单中,请向其中添加以下内容(假设 Category
具有 name
属性):
<%= f.select :categories, Category.pluck(:id, :name), {}, multiple: true %>
另外不要忘记在允许的参数中将类别列入白名单 (posts_controller.rb
):
def post_params
params.require(:post).permit(:attr1, :attr2, category_ids: [])
end
在您的 post.rb 模型中,添加 scope:
scope :animals, -> { where(category: 'Animals') }
然后在你的控制器中,你可以调用:
Post.all.animals
我目前有一个 posts 模型,其中有一个 category:string 列。我希望显示某些类别中的所有帖子。
例如单击 'Technology' 类别 link - 加载所有类别为 apple 的帖子。
在堆栈溢出上找不到任何东西,但我可能找错了东西。任何帮助将不胜感激!
谢谢
Post.where(category: 'Animals')
将 return 所有具有指定类别的 post。
关于问题下的评论 - 是的,您可以从额外的模型中受益 Category
,因为 post 可以有多个类别。
您可以将关系定义为以下之一:
HBTM
has_and_belongs_to_many :categories # post.rb has_and_belongs_to_many :posts # category.rb
has_many到
post.rb
has_many :categories_posts
has_many :categories, through: :categories_posts
category.rb
has_many :categories_posts
has_many :posts, through: :categories_posts
categories_posts.rb
belongs_to :category
belongs_to :post
编辑
要将选择类别添加到表单中,请向其中添加以下内容(假设 Category
具有 name
属性):
<%= f.select :categories, Category.pluck(:id, :name), {}, multiple: true %>
另外不要忘记在允许的参数中将类别列入白名单 (posts_controller.rb
):
def post_params
params.require(:post).permit(:attr1, :attr2, category_ids: [])
end
在您的 post.rb 模型中,添加 scope:
scope :animals, -> { where(category: 'Animals') }
然后在你的控制器中,你可以调用:
Post.all.animals