我正在使用一个ApplicationHelper方法,在我的视图中将时间对象转换为“人性化”时间度量:
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
它工作得很好,但我在翻译一个方法的最终结果时遇到了一个问题,该方法旨在列出指定位置的时间间隔:
RFIDTag.rb:
def time_since_first_tag_use
product_selections.none? ? "N/A" : Time.now - product_selections.order(staged_at: :asc).first.staged_at
end
Product.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
同时,尝试在产品模型中应用该方法
第一个阶段标签
方法在上生成NoMethod错误
humanize_seconds
. 如何获取时间列表以识别时间转换?
所有尝试的重复都在评论中。