Rails视图段取决于udpated_at / created_at时间?

时间:2016-01-06 18:27:21

标签: ruby-on-rails time

我可以在为新闻报道添加标签的过程中执行此操作:

<% if article.urgency == 'majorbreaking' && article.updated_at.today? %>
  <span class="breaking">
…

开箱即用'今天',但我怎么做(比如说)“过去六个小时”(在一个视图中,我知道如何使用范围和控制器来选择文章,但这是在选择之后,仅针对视图)。

感谢。

3 个答案:

答案 0 :(得分:2)

因为这是在选择之后,我们可以像这样使用:

article.updated_at >= 6.hours.ago

简单&amp;相当

答案 1 :(得分:2)

您可以通过在文章模型中创建方法来最小化视图正在处理的硬编码逻辑,并可能干扰您的代码(如果实际上您想要处理多个时间跨度)。例如:

class Article < ActiveRecord::Base 
  def recent?(hours_ago=24)
    created_at >= hours_ago.hours.ago
  end
end

然后在你看来:

在最后一天内:

<% if article.urgency == 'majorbreaking' && article.recent? %>
  <span class="breaking">

在过去6小时内:

<% if article.urgency == 'majorbreaking' && article.recent?(6) %>
  <span class="breaking">

答案 2 :(得分:1)

如果您想在过去6小时内替换at_today,请使用:

<% if article.urgency == 'majorbreaking' && article.updated_at > (DateTime.now - 6.hours) %>
  <span class="breaking">
…

检查时间助手

http://api.rubyonrails.org/classes/DateTime.html http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html http://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html