如何从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
那是我完成的工作。
示例之后是我想要的
技术(家长)
教育(家长)
其他(家长)
请帮助我完成这项工作。
由于
答案 0 :(得分:0)
您在帮助程序中使用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