2010-09-22 54 views
1

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 => '>' %> 

这一观点的目的是显示每个标签的最新帖子。每发布一条评论,帖子的updated_at时间戳就会更新。

它显示的帖子这个排序:

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

谁能告诉我,为什么上面的代码显示在其中创建自己的标签顺序的职位?

回答

1

你打电话分页桩的阵列上,这样的顺序是一样的阵列的。如果你不能确保阵列中创建瓦特/对象进行排序,你所希望的方式,你可以随时调用PAGINATE之前对其进行排序:

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

你应该某处指定的顺序:

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

'@posts = @ posts.paginate:page => params [:page],:per_page => 8,:order =>'updated_at DESC''不改变顺序。我也在'home#index'中尝试了所有其他'@ posts' – BasicObject 2010-09-22 21:12:11

+0

它不起作用,因为当你分页时你有所有的帖子......也许你可以在你的post模型中定义 - > default_scope:order =>'id DESC' – jordinl 2010-09-22 21:23:05

+0

我宁愿使用默认范围,但它不起作用。尽管如此,avaynshtok的方法。 – BasicObject 2010-09-24 02:45:40

0

放置在指数

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

此代码段它应该工作。

相关问题