开发者

grouping and displaying by dates

I have a rails application and I want to display messages (Message) to the user based on the time the messages have arrived

every message (Message) has a property called created_at

for example -- 20 minutes ago -----message1 -----message2

-- 1 hour ago -----message3 -----message4 -----message5开发者_运维问答

-- 2 days ago -----message6

and so on and so forth.

how can I do this using rails?

I am using rails 3 b.t.w


You basically have two options. The first is to use the built-in Rails helper time_ago_in_words:

# in your views
<%= time_ago_in_words(message.created_at) %>

You can read more about this helper in the Rails documentation.

The downside with this is that it only works in views, and it might not be the entirely correct format. If that's the case, you can always define your own helper in an initializer. Here's a method I coded up for an old app, which you should be able to modify to suit your requirements:

class ActiveSupport::TimeWithZone
  def how_long_ago
    seconds = (Time.now - self)

    # Keep adding days, weeks, months, years if necessary--same principle should apply
    if seconds > 3600
      (seconds / 3600).to_i.to_s + "h " + (seconds % 3600 / 60).to_i.to_s + "m"
    elsif seconds > 60
      (seconds / 60).to_i.to_s + "m " + (seconds % 60).to_i.to_s + "s"
    else
      seconds.to_i.to_s + "s"
    end
  end
end

Message.first.created_at.how_long_ago # => 3m 52s

To group the data based on this, you can use the group_by method on the messages array.


You can set default scope in your Message model:

default_scope order('messages.created_at DESC')


I found an answer on RailsCasts which is perfect for my needs

http://railscasts.com/episodes/29-group-by-month

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜