开发者

Why doesn't this view display posts in descending order? (simple question)

开发者 https://www.devze.com 2023-01-17 09:02 出处:网络
home_controller.rb: class HomeController < ApplicationController def index @title = \"tags\" @posts = Post.tag_counts.collect do |tag|

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 @pos开发者_StackOverflow社区ts, :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?


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)


You should specify the order somewhere:

@posts = Post.all(:order => 'id DESC')


Place this code snippet in Index

@posts = Post.all.order('created_at DESC')

It should work.

0

精彩评论

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