ruby-on-rails - 转换为 DateTime 方法切断列表呈现(Rails)
问题描述
在我看来,我正在使用一种 ApplicationHelper 方法,该方法将 Time 对象转换为“人性化”时间测量:
def humanize_seconds s
if s.nil?
return ""
end
if s > 0
m = (s / 60).floor
s = s % 60
h = (m / 60).floor
m = m % 60
d = (h / 24).floor
h = h % 24
w = (d / 7).floor
d = d % 7
y = (w / 52).floor
w = w % 52
output = pluralize(s, "second") if (s > 0)
output = pluralize(m, "minute") + ", " + pluralize(s, "second") if (m > 0)
output = pluralize(h, "hour") + ", " + pluralize(m, "minute") if (h > 0)
output = pluralize(d, "day") + ", " + pluralize(h, "hour") if (d > 0)
output = pluralize(w, "week") + ", " + pluralize(d, "day") if (w > 0)
output = pluralize(y, "years") + ", " + pluralize(w, "week") if (y > 0)
return output
else
return pluralize(s, "second")
end
end
它工作得很好,但是在翻译旨在列出指定位置的时间间隔的方法的最终结果时遇到了问题:
RFID标签.rb:
def time_since_first_tag_use
product_selections.none? ? "N/A" : Time.now - product_selections.order(staged_at: :asc).first.staged_at
end
产品.rb:
def first_staged_tag
rfid_tags.map { |rfid| rfid.time_since_first_tag_use.to_i }.join(", ")
end
查看:(html.erb):
将值放在那里first_staged_tag
是可行的,并按预期列出值,但它只在几秒钟内完成:
<% @products.order(created_at: :desc).each do |product| %>
<td><%= product.name %></td> #Single product name
<td><%= product.first_staged_tag %></td> list, i.e. #40110596, 40110596, 39680413, 39680324
<%end%>
在以通常的方式转换时<td><%= humanize_seconds(product.first_staged_tag) %></td>
,对于单个值有效,会出现此错误:
comparison of String with 0 failed
Extracted source (around line #88):
86 return ""
87 end
88 if s > 0
89 m = (s / 60).floor
90 s = s % 60
91 h = (m / 60).floor
同时,尝试在 Product 模型first_staged_tag
方法中应用该方法会在 上生成 NoMethod 错误humanize_seconds
。如何获取时间列表以识别时间转换?
所有尝试的迭代都在评论中。
解决方案
解决了!标签必须映射到 Product 模型中,并在那里转换:
#Product.rb
def first_staged
rfid_tags.map { |rfid| rfid.time_since_first_tag_use.to_i }
end
然后在整个视图中再次迭代:
<%= product.first_staged.map {|time| humanize_seconds(time) }.join(", ") %>
推荐阅读
- ckeditor - 如何避免ckfinder重新处理图像?
- javascript - 带有classyloader的猫头鹰轮播圆形进度条给出getContext错误
- excel - 遍历集合
- c# - CollisionOnEnter 如何检测物体是否发生碰撞?
- assembly - mulw、prodl 和 prodh 在汇编程序中如何协同工作?
- python - 根据键值存储到“@myID”的路由
- r - 在 open.connection(x, "rb") 中出现错误:HTTP 错误 504.while Web 抓取使用 rvest
- postgresql - 获取表中的列名列表(PostgreSQL)
- python-3.x - python函数中标题的自动化
- javascript - 反应库代码中的花括号是什么意思?