我正在使用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
效果很好,但是在翻译设计用于在指定位置列出时间间隔的方法的最终结果时,我遇到了一个问题:
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
同时,尝试在产品模型first_staged_tag
中应用该方法会在humanize_seconds
上产生NoMethod错误。如何获取时间列表以识别时间转换?
所有尝试的迭代都在注释中。
答案 0 :(得分:0)
解决了!标签必须在产品模型中进行映射,并在那里进行转换:
#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(", ") %>