Ruby on rails 如何显示所有子类别';s posts而不是";。第一个RubyonRails
我有一个包含子类别/主类别的博客,在主类别上,我希望它列出所有子类别的帖子。我使用方法Ruby on rails 如何显示所有子类别';s posts而不是";。第一个RubyonRails,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个包含子类别/主类别的博客,在主类别上,我希望它列出所有子类别的帖子。我使用方法。首先,但我不知道如何以我需要的方式处理这个问题 博客类别模型: class BlogCategory < ApplicationRecord extend FriendlyId friendly_id :name, use: :slugged has_many :posts # This is called a self referential relation. This is wh
。首先,但我不知道如何以我需要的方式处理这个问题
博客类别模型:
class BlogCategory < ApplicationRecord
extend FriendlyId
friendly_id :name, use: :slugged
has_many :posts
# This is called a self referential relation. This is where records in a table may point to other records in the same table.
has_many :sub_categories, class_name: "BlogCategory", foreign_key: :parent_id
belongs_to :parent, class_name: 'BlogCategory', foreign_key: :parent_id
# This is a scope to load the top level categories and eager-load their posts, subcategories, and the subcategories' posts too.
scope :top_level, -> { where(parent_id: nil).includes :posts, sub_categories: :posts }
def should_generate_new_friendly_id?
slug.nil? || name_changed?
end
end
def show
@cat = BlogCategory.friendly.find(params[:id])
@category = @cat.parent
@posts = @cat.posts
@sub_category = @cat.sub_categories.first
unless @sub_category.nil?
@relatives = @sub_category.posts
end
end
private
def cat_params
params.require(:blog_category).permit(:name, :parent_id, :sub_category)
end
def main_cat
@cat = BlogCategory.parent_id.nil?
end
帖子模式:属于:博客类别
我尝试了一些.all
.each
的配置,并查看.collection
是否有效,但这些似乎并没有解决我的问题
谢谢你,我非常感谢。我想你想要所有的帖子。如果一篇文章属于某个类别,那么该类别将是另一个类别的子类别,最终,您将拥有主类别,因此,您可以执行以下操作:
@cat.descendants # array of all children, children's children, etc., excluding self
@posts=Post.where.not(博客类别:nil)
如果您有许多主要类别,每个博客一个,那么您需要实现一个递归方法
您也可以使用https://github.com/collectiveidea/awesome_nested_set
然后执行以下操作:
@cat.descendants # array of all children, children's children, etc., excluding self
您可以像这样在类别模型中添加一个具有多个关联的
has_many :sub_category_posts, through: :sub_categories, source: :posts
在控制器中
@relatives = @cat.sub_category_posts
哇,太谢谢你了!我没有意识到这是实现这一点的一种方式。我有5个主要类别,大多数类别都有2个或更多子类别,基于指向主要类别的父类id
。