Ruby on rails 未定义的方法`子类别';零级:零级

Ruby on rails 未定义的方法`子类别';零级:零级,ruby-on-rails,ruby,Ruby On Rails,Ruby,我试图为我的博客建立一个分类系统,但我遇到了这个错误。每个blog\u类别可以有多个子类别,方法是将parent\u id指向主类别的id。一些子类和主博客类中没有任何内容。如何防止此NoMethodError命中 BlogCategoriesController: class BlogCategoriesController < ApplicationController def index @category = BlogCategory.find_by_id(params[:i

我试图为我的博客建立一个分类系统,但我遇到了这个错误。每个
blog\u类别
可以有多个子类别,方法是将
parent\u id
指向主类别的id。一些
子类
和主
博客类
中没有任何内容。如何防止此
NoMethodError
命中

BlogCategoriesController:

class BlogCategoriesController < ApplicationController

def index
  @category = BlogCategory.find_by_id(params[:id])
  @sub_category = @category.sub_categories.first
  @posts = @subcategory.posts
end

private

  def cat_params
    params.require(:blog_category).permit(:name, :parent_id, :sub_category)
  end

end
class BlogCategoriesController
博客类别模型:

class BlogCategory < ApplicationRecord
  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

  # 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 }
end
class-BlogCategory{where(父级id:nil)。包括:帖子、子类别::帖子}
终止

帖子通过post表中的
t.integer“blog\u category\u id”
指向博客类别,并且在帖子模型中有一个
属于:blog\u category

您可以添加验证

def index
  @category = BlogCategory.find_by_id(params[:id])
  unless @category.nil?
      @sub_category = @category.sub_categories.first
      @posts = @subcategory.posts
  end
end

您正在执行哪些导致错误的代码?你能显示堆栈跟踪吗?假设错误发生在你的
索引中:
@sub_category=@category.sub_categories。首先
,那么你的错误与你的关联无关。相反,显然,
BlogCategory.find_by_id(params[:id])
返回了
nil
,如错误中所述,不响应
子类
@category
可以是
nil
,因为
find\u by
-使用
find
,在这种情况下rails将自动引发
404 not found