如何显示来自 rails 帮助程序内容标签的组织数据

How to show organized data from rails helper content tag

How to show organized data from rails helper content tag?

如下是我的辅助方法,我想显示按 parent 分组的所有类别名称,即 ul li 如果可以,请看下面的方法我认为您将了解该代码以及我想要什么。该方法输出数据但不使用 ul li

辅助方法

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

那是我完成的作品。

例子之后就是我想要的样子

技术 (Parent)

教育 (Parent)

其他 (Parent)

请帮我完成这项工作。

谢谢

您在帮助程序中使用了 ERB,但它不是 html.erb 文件,因此您无法获取要创建的标签。为什么不直接使用您生成的哈希,然后我认为您正在寻找的是这样的东西:

辅助方法:

def category
  Category.select(:id, :name, :parent).group_by(&:parent)
end

然后在您的视图文件 (.html.erb) 中执行如下操作:

  <% category.each do |cat, list| %>
    <div class="category">
      <b> <%= cat %> </b>
      <ul>
        <% list.each do |item| %>
          <li> <%= item.name %> </li>
        <% end %>
      </ul>
    </div>
    <br>
  <% end %>

好的,你可以根据文档使用concat方法按照你建议的方式进行:

def category
    parent_categories = Category.select(:id, :name, :parent).group_by(&:parent)
    parent_categories.each do |parent, childs|
        concat content_tag(:div) do 
           concat content_tag(:h1, parent)
        end 
       concat content_tag(:ul) do 
            childs.each do |child|
               concat content_tag(:li, child.name)
            end
        end
    end
end