inf*_*ity 3 html ruby hash ruby-on-rails
我有一个名为"products"的数据库,它有一个使用hstore调用的字段data
.
目前,在我的index.html.haml中,我只是循环浏览产品并将其显示data
为哈希:
- @products.each do |product|
=product.data #THIS PRINTS A HASH
%hr
Run Code Online (Sandbox Code Playgroud)
例如,哪个可以打印哈希,如:
{"Name"=>"Example","type"=>"book", "price"=>"7.99"}
Run Code Online (Sandbox Code Playgroud)
我想创建一个可以保存动态数量的键和值的HTML表,并将它们打印到具有与键对应的值的列中.这是一个图表:
谢谢大家的帮助!
希望这可以帮助:
条件:
代码:
# headers
%tr
- @products.first.data.keys.each do |attribute_name|
%th= attribute_name
# body
- @products.each do |product|
%tr
- product.data.attributes.each do |attribute_value|
%td= attribute_value
Run Code Online (Sandbox Code Playgroud)
如果每个product.data
键具有相同数量的键/值对并且以相同顺序存储,则此代码将正确呈现.
条件:
代码:
# we gather all possible attribute's name in the data hash:
- headers = @products.map(&:data).flat_map(&:keys).uniq
%tr
# we make a table-head cell for each attribute's name:
- headers.each do |key|
%th= key
- @products.each do |product|
%tr # for each attribute's name, we display a TD cell and try to display it's value if exists
- headers.each do |key|
%td= product.data[key]
Run Code Online (Sandbox Code Playgroud)
随意询问细节,我觉得我刚给你一段代码而没有任何解释......