views:

32

answers:

2

home_controller.rb:

class HomeController < ApplicationController

  def index
    @title = "tags"
    @posts = Post.tag_counts.collect do |tag|
      Post.tagged_with(tag).first
    end
    @posts.flatten.uniq
    @posts = @posts.paginate :page => params[:page], :per_page => 8

  end

end

index.html.erb:

<%- for post in @posts -%>

  <%- post.tags.each do |t| -%>
    <%= link_to t.name, tag_path(t) %>
  <%- end -%>

  <%= link_to post.title, post %>

  <%- if post.comments.empty? -%>

  <% else %>

    <%= link_to pluralize(post.comments.count, 'reply'), :controller => 'posts', :action => 'show', :id => post %>

  <%- end -%>

  <%= timeago(post.updated_at) %>

<%- end -%>

<%= will_paginate @posts, :previous_label => '<', :next_label => '>' %>

This view's purpose is to show the latest post of each tag. The updated_at timestamp of a post is updated each time that post is commented on.

it's displaying posts with this ordering:

 tag id = 1
 tag id = 2
 tag id = 3
          ...

Can anyone tell me why the code above displays the posts in the order in which their tags were created?

A: 

You should specify the order somewhere:

@posts = Post.all(:order => 'id DESC')
jordinl
`@posts = @posts.paginate :page => params[:page], :per_page => 8, :order => 'updated_at DESC'` doesn't change the order. I've also tried it with all the other `@posts` in `home#index`
It won't work because by the time you paginate you have all the posts... maybe you could define in your post model --> default_scope :order => 'id DESC'
jordinl
I would have preferred to use the default scope but it didn't work. avaynshtok's method did though.
+1  A: 

You're calling paginate on an array of posts, so the ordering is the same as the array's. If you can't ensure that the array is created w/ the objects sorted the way you want, you can always sort it before calling paginate:

@posts = @posts.sort_by(&:updated_at)
avaynshtok