【发布时间】:2025-12-05 00:05:01
【问题描述】:
如何从 rails helper 内容标签显示有组织的数据?
如下是我的辅助方法,我想显示按父级分组的所有类别名称,即ul li 如果你可以请看下面的方法,我想你会理解代码和我想要什么.该方法输出了数据,但没有ulli
辅助方法
def category
parent_categories = Category.select(:id, :name, :parent).group_by(&:parent)
parent_categories.each do |parent, childs|
content_tag(:div) do
content_tag(:h1, parent)
end +
content_tag(:ul) do
childs.each do |child|
content_tag(:li, child.name)
end
end
end
end
<%= category %>的输出
{"Technology"=>[#<Category id: 1, name: "Programming", parent: "Technology">, #<Category id: 3, name: "Ruby on Rails", parent: "Technology">, #<Category id: 9, name: "Full Time", parent: "Technology">, #<Category id: 14, name: "Business Opportunities", parent: "Technology">, #<Category id: 15, name: "Contract & Freelance", parent: "Technology">, #<Category id: 18, name: "Engineering", parent: "Technology">, #<Category id: 25, name: "IT", parent: "Technology">],
"Education"=>[#<Category id: 5, name: "Industry", parent: "Education">, #<Category id: 6, name: "Education", parent: "Education">, #<Category id: 7, name: "Education & Industry", parent: "Education">, #<Category id: 16, name: "Customer Service", parent: "Education">, #<Category id: 17, name: "Diversity Opportunities", parent: "Education">],
"Other"=>[#<Category id: 8, name: "Part Time", parent: "Other">, #<Category id: 12, name: "Admin & Clerical", parent: "Other">]}
schema.rb
create_table "categories", force: :cascade do |t|
t.string "name"
t.string "parent"
end
这是我完成的工作。
后面的例子是我想要的样子
技术(家长)
- 编程
- Ruby on Rails
- 红宝石
- ReactJS
教育(家长)
- 办公室
- 老师
- 物理
其他(家长)
- 临床
- 健康
- 等等...
请帮我完成这项工作。
谢谢
【问题讨论】:
-
试试
.collect而不是each -
您是希望类别引用另一个类别作为父类别还是只是预定义的字符串?
标签: ruby-on-rails ruby helper