首页 > 解决方案 > 如何从 rails helper 内容标签显示有组织的数据

问题描述

如何从 rails helper 内容标签显示有组织的数据?

如下所示是我的辅助方法,我想显示按父级分组的所有类别名称,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

那是我完成的工作。

示例之后是我想要的

技术(父)

教育(家长)

其他(父母)

请帮我完成这项工作。

谢谢

标签: ruby-on-railsrubyhelper

解决方案


您在帮助程序中使用了 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

推荐阅读