简体   繁体   English

Rails 3 - ActiveRecord和反向排序

[英]Rails 3 - ActiveRecord and reverse sort

I have following data in database: 我在数据库中有以下数据:

1
2
3
4
5

And I would like to get to output this: 我想输出这个:

3
4
5

I need it to print in the view: 我需要它在视图中打印:

<%car.colors.limit(3).order('created_at ASC').each do |color|%>
  ...

I know that exists reverse_order , but exist something like reverse sort ? 我知道存在reverse_order ,但存在类似反向排序的东西?

(I know that is possible to load the data into an array and then go through the array, but this way is not very efficient) (我知道可以将数据加载到数组中然后遍历数组,但这种方式效率不高)

刚做的怎么样

<%car.colors.limit(3).order('created_at DESC').reverse.each do |color|%>

For Rails 4: 对于Rails 4:

[Model].order(column: :desc)

For Rails 3: 对于Rails 3:

[Model].order("<column> DESC")

For Rails 2: 对于Rails 2:

[Model].all(:order => "<column> DESC")

One line Solution 一线解决方案

in your controller use: 在您的控制器中使用:

class Api::ImagesController < ApplicationController

  def index
    @posts =  Post.all.paginate(:page => params[:page], :per_page => 4).order(id: :desc)
    render :json => @posts.to_json(:methods => [:image_url])
  end

end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM