Mongoid Rails 4按asc或desc命令created_at排序

时间:2014-06-04 11:58:26

标签: sorting date ruby-on-rails-4 mongoid

我有一个使用Mongoid的rails 4 app。 我想做一些基本的事情是根据索引视图中的字段created_at以降序显示我拥有的书模型。 在控制器books_controller.rb中:

def index
  @books = Book.order_by(:created_at.desc)
end

这不起作用。我还尝试了以下2个无效的方法:

@books = Book.find :all, :order => "created_at DESC"

Book.find(:all, :order => "created_at DESC").each do |item|
  @books << item
end

在视图中我有这样的事情:

<% @books.each do |b| %>
  ...
<% end %>

谢谢。

5 个答案:

答案 0 :(得分:53)

你可以试试这个

def index
  @books = Book.order_by(created_at: :desc)
end

它工作正常。

答案 1 :(得分:4)

def index
   @books = Book.order(:created_at => 'desc')
end

它适用于我,而不是order_by使用顺序(取决于rails版本)

答案 2 :(得分:2)

您可以同时使用&#34; order&#34;和&#34; order_by&#34;,它们是等价的。 所有这些都是等价的:

Book.order_by(created_at: :desc)
Book.order_by(created_at: -1)
Book.order(created_at: :desc)
Book.order(created_at: -1)

这是来自mongoid 5.1.3&#34; lib / mongoid / criteria / queryable / optional.rb&#34;的源代码:

# Adds sorting criterion to the options.
#
# @example Add sorting options via a hash with integer directions.
#   optional.order_by(name: 1, dob: -1)
#
# @example Add sorting options via a hash with symbol directions.
#   optional.order_by(name: :asc, dob: :desc)
#
# @example Add sorting options via a hash with string directions.
#   optional.order_by(name: "asc", dob: "desc")
#
# @example Add sorting options via an array with integer directions.
#   optional.order_by([[ name, 1 ], [ dob, -1 ]])
#
# @example Add sorting options via an array with symbol directions.
#   optional.order_by([[ name, :asc ], [ dob, :desc ]])
#
# @example Add sorting options via an array with string directions.
#   optional.order_by([[ name, "asc" ], [ dob, "desc" ]])
#
# @example Add sorting options with keys.
#   optional.order_by(:name.asc, :dob.desc)
#
# @example Add sorting options via a string.
#   optional.order_by("name ASC, dob DESC")
#
# @param [ Array, Hash, String ] spec The sorting specification.
#
# @return [ Optional ] The cloned optional.
#
# @since 1.0.0
def order_by(*spec)
  option(spec) do |options, query|
    spec.compact.each do |criterion|
      criterion.__sort_option__.each_pair do |field, direction|
        add_sort_option(options, field, direction)
      end
      query.pipeline.push("$sort" => options[:sort]) if aggregating?
    end
  end
end
alias :order :order_by

答案 3 :(得分:2)

Book.where(作者:“Stephen King”)。sort({“created_at”:1}) - &gt;升序

Book.where(作者:“Stephen King”)。sort({“created_at”:-1}) - &gt;降序

答案 4 :(得分:0)

def index
  @books = Book.desc(:created_at)
end

它工作正常。