繁体   English   中英

如何显示所有子类别的帖子,而不是“ .first” | Ruby on Rails

[英]How to display all subcategory's posts instead of “.first” | Ruby on Rails

我有一个博客,其中包含子类别/主要类别,并且在主要类别中,我希望它列出其所有子类别中的帖子。 我使用.first方法工作,但是我只是不知道如何以我需要的方式处理它。

BlogCategory模型:

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

blog_categories控制器:

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

帖子模型: belongs_to :blog_category

我已经试过的一些配置.all .each和观察,如果.collection的工作,但这些似乎并没有解决我的问题。

谢谢,我很感激。

我想你想要所有的职位。 如果帖子属于某个类别,则该类别将是另一个类别的子类别,最终,您将拥有主要类别,因此,您可以执行以下操作:

@posts = Post.where.not(blog_category: nil)

如果您有许多主要类别,每个博客一个,则需要实现一种递归方法。

您还可以使用https://github.com/collectiveidea/awesome_nested_set并执行以下操作:

@cat.descendants # array of all children, children's children, etc., excluding self

https://github.com/collectiveidea/awesome_nested_set/wiki/Awesome-nested-set-cheat-sheet

您可以像这样在您的类别模型中添加一个具有多个关联的对象

has_many :sub_category_posts, through: :sub_categories, source: :posts

在您的控制器中

@relatives = @cat.sub_category_posts

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM