转换为 DateTime 方法切断列表呈现 (Rails)

Conversion to DateTime method cutting off list rendering (Rails)

我正在使用 ApplicationHelper 方法将 Time 对象转换为我认为的 'humanized' 时间测量值:

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

同时,尝试在 Product 模型 first_staged_tag 方法中应用该方法会在 humanize_seconds 上生成 NoMethod 错误。我怎样才能得到我的时间列表来识别时间转换?

所有尝试的迭代都在评论中。

已解决!标签必须映射到 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(", ") %>