【问题标题】:Set expiration date and time with before_create Rails 4使用 before_create Rails 4 设置到期日期和时间
【发布时间】:2014-12-12 11:59:02
【问题描述】:

我正在为广告添加过期功能。 Expire 应该包含数据和时间像这样:12.06.12 14:24

此时我是这样做的: 我在数据库中有一个名为 expiration

的广告的附加列
before_create :set_expiration_date

   def set_expiration_date
        self.expiration =  Date.today + 56.days
    end

这很好用。现在在视图中,我想查看此到期日期。

广告#show

<%= @advertisement.expiration.to_formatted_s(:db) %>

但它给了我这个2015-02-06

当我将 set_expiration_date 更改为:

 def set_expiration_date
      self.expiration =  Time.now + 56.days
 end

那仍然像2015-02-06没有时间。

所以我想知道是否只有灵魂解决方案在我的广告表中有两列 expiration_dateexpiration_time

然后在我的模型中有这样的:

 before_create :set_expiration_date
 before_create :set_expiration_time


 def set_expiration_date
      self.expiration_date =  Date.today + 56.days
 end

 def set_expiration_time
      self.expiration_time =  Time.now
 end

我觉得这个解决方案很丑。

我的问题还有其他更简单的解决方案吗?如何存储单列日期和时间?

提前致谢!

【问题讨论】:

  • expiration_time 列的格式是什么?是datetime吗?请出示您的迁移文件。

标签: ruby-on-rails datetime


【解决方案1】:

Changeexpiration的数据类型从datedatetime

【讨论】:

    【解决方案2】:

    expirationdate 更改为datetime,为什么不使用strftime 来更好地格式化输出

    示例:

    <%= @advertisement.expiration.strftime("%b %d %Y, %H:%M") %>
    

    另见strftime format meaning

    【讨论】:

      猜你喜欢
      • 2018-11-01
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      相关资源
      最近更新 更多