0

我想将从以下格式返回的字符串更改为显示自上次从客户下订单以来的几个月天数的日期,我在页面上有以下代码来获取结果 -

<% @lastorder = Order.select("DateCreated").where("customer_id == ?", customer.id).order("Datecreated desc").find(:all, :limit => 1) %>

但这会返回以下格式 -

 [#<Order DateCreated: "2013-01-09 00:00:00">]

可能有更好的方法来做到这一点,但我目前不知道。

4

1 回答 1

1

我会这样重写你的查询:

@last_order = Order
  .where(customer_id: customer.id) # No need to use prepared statement here
  .order('DateCreated DESC')
  .pluck('DateCreated')            # Directly select 1 column
  .first()                         # Only select the first record

如果你想用文字显示时间距离,你应该使用 rails helper :distance_of_time_in_words_to_now(@last_order)

信息:只要发现 thandistance_of_time_in_words_to_now是 的别名time_ago_in_words,更短。

于 2013-02-05T10:36:47.847 回答