Descending Sort By in Model For Active Record Hash on Created_at attribute

If you have a couple collections from the database and you want to sort it without the help of Active Record, take a look at the sort_by method on Array type. I’ve used this before when I have a couple of collections which are slightly different but I need them in a chronological order.


  @posts_group_a = Post.find :all, :conditions => ["user_id = ?", current_user.id]
  @posts_group_b = Post.find :all, :conditions => ["user_id = ?", friend_user.id]

  #merge the two arrays here
  @posts = @posts_group_a + @posts_group_b

  # notice the "-" is for descending order and the "to_i" casts the date time to an integer (required)
  @posts.sort_by {|post| - post.created_at.to_i}

Related posts:

  1. Active Record Find Methods
  2. Override to_param method in model to get pseudo permalinks without any work
  3. Rails Helper to Remove Leading Zero in 12 Hour Time Format
This entry was posted in Ruby on Rails and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>