1

路线.rb

root :to => 'articles#index'

微贴模型:

class Micropost < ActiveRecord::Base
  attr_accessible :content, :user_id
  belongs_to :user
  validates :user_id, presence: true
  validates :content, presence: true, length: { maximum: 100 }
end

文章型号:

class Article < ActiveRecord::Base
  attr_accessible :content, :title

  validates :title, :presence => true,
                :length => { :minimum => 2 }  
  belongs_to :user
end

以及articles_controller.rb 的索引define_method

def index
  @articles = Article.paginate(:page => params[:page], 
                       :per_page => 5,
                       :order => 'created_at DESC')


  respond_to do |format|
    format.html 
    format.json { render json: @articles }
  end
end

虽然我不怎么写我的articles_controller#index 和索引视图。

4

2 回答 2

0

究竟是什么问题?

如果您希望所有文章都在一个页面上,请不要使用分页,而是:

Article.all

如果您希望按 created_at 时间戳降序排列的所有文章:

Article.order("created_at DESC")

或者您是否想要具有不同顺序的第二页?然后我会创建一个新的路由,它接受一个参数来告诉操作你想要哪种排序。然后在控制器内部:

if(params[:order_by_created_time])
  # ...
else
  # ... 
end

respond_to do |format|
  # ...
end

如果您的视图已经在工作(并显示微博):

def index
  @articles = Article.order("created_at DESC")

  respond_to do |format|
    format.html 
    format.json { render json: @articles }
  end
end
于 2013-03-05T14:55:01.007 回答
0

鉴于您的代码有效,您应该能够简单地更改updated_atcreated_at

def index
  @posts = Post.paginate(:page => params[:page], 
                       :per_page => 5,
                       :order => 'created_at DESC')

  respond_to do |format|
    format.html 
    format.json { render json: @posts }
  end
end
于 2013-03-05T14:56:38.493 回答