【发布时间】:2018-06-18 15:45:50
【问题描述】:
我有一个blog_categories 表,其中sub_categories 基于指向主类别.id 的parent_id 值,该值位于子类别之上。主要类别有 parent_id 和 NULL。这都是通过自指关系完成的。
如何在基于/blog_categories/#的blog_categories.show视图中显示当前sub_category和父blog_category的名称?
例如;
- “新闻”拥有
.id1 和parent_idNULL,因为它是主要类别。- “Good” 具有
.id2 和parent_id1,因为它属于.id为 1 的类别。- “坏” 具有
.id3 和parent_id1,因为它属于.id为 1 的类别。当
/blog_categories/2被渲染时,我试图让它显示 子类别的名称(在本例中为 "Good"),后跟其 父类别(在本例中为“新闻”)。期望的结果是一个标明“好消息”
的标题
BlogCategory 型号:
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
Blog_categories控制器:
class BlogCategoriesController < ApplicationController
def index
@categories = BlogCategory.top_level.includes(sub_categories: :posts)
@category = BlogCategory.find_by_id(params[:id])
unless @category.nil? # Allows for categories to have nothing in them, eliminating the NoMethodError
@sub_category = @category.sub_categories.first
@posts = @subcategory.posts
end
@all_posts = Post.all
end
def show
@category = BlogCategory.find_by_id(params[:id])
@sub_category = @category.sub_categories
@posts = @category.posts
end
private
def cat_params
params.require(:blog_category).permit(:name, :parent_id, :sub_category)
end
end
我的显示视图:
<% BlogCategory.top_level do |category| %>
<% category.sub_categories do |sub_category| %>
<h2 class="center p-space blog-h2"><%= sub_category.name %> <%= category.name %></h2>
<% end %>
<% end %>
我尝试了do 语句的几种组合,但我真的无法解决这个问题。我希望得到一些帮助来解决这个问题,谢谢!
如果这有帮助,我在 <%= @category.name %> 上取得了一些成功,但它只显示子类别的名称。
【问题讨论】:
标签: ruby-on-rails ruby