ruby-on-rails - 如何从 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 Rails
- 红宝石
- 反应JS
教育(家长)
- 办公室
- 老师
- 物理
其他(父母)
- 临床
- 健康
- ETC...
请帮我完成这项工作。
谢谢
解决方案
您在帮助程序中使用了 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
推荐阅读
- android - 不同的 SHA1 密钥 (Android)
- angularjs - 使用 nodejs 的 LDAP 身份验证
- c++ - Makefile“运行”产生错误,但手动执行不会
- javascript - 火狐和
我有图像按钮的样式:
.sticky { position: fixed; top: 50px; width: 120%; z-index: 1; } @media screen and (min-device-width : 100px) and (max-width:
- php - 设置 cookie 每次用户点击按钮时 cookie 名称加 1
- php - PHP减少几秒钟的“日期时间”
- arduino - CASE 步进红外遥控器和 Arduino
- variables - 初始化变量 OCaml
- java - 检查Java中的图像是否为空白
- excel - 在excel中将持续时间减少一个百分比