order_by 在 Mongoid 中沿着 find_by,NoMethodError - 未定义的方法“order_by”

order_by in Mongoid along find_by, NoMethodError - undefined method `order_by'

我必须使用 Mongoid 在 sinatra 应用程序中检索 mongodb 记录。 为此,我尝试使用以下查询对检索到的记录进行排序:

@bin = Bin.find_by(bin_id: params[:bin_id]).order_by(:created_at.desc)

但是我遇到了 NoMethodError,

NoMethodError - undefined method `order_by' for #<Bin:0x00000101d24d60>:
/Users/harshsingh/Documents/Codes/mogreet-requestbin/app.rb:79:in `block in <class:App>'
/Users/harshsingh/.rvm/gems/ruby-2.1.2/gems/sinatra-1.4.5/lib/sinatra/base.rb:1603:in `call'
/Users/harshsingh/.rvm/gems/ruby-2.1.2/gems/sinatra-1.4.5/lib/sinatra/base.rb:1603:in `block in compile!'
/Users/harshsingh/.rvm/gems/ruby-2.1.2/gems/sinatra-1.4.5/lib/sinatra/base.rb:966:in `[]'
...

我不确定为什么 order_by 不起作用,我尝试查看 Mongoid 文档但找不到任何对我有帮助的东西。

编辑:

对不起,我忘了说,我在 Bin 文档中有一个嵌入文档,名为 Callback,具有 embeds_many :callbacksembedded_in :bin, :inverse_of => :bins 的关系,所以我想根据 created_at.

在一个特定的 bin 中对 callbacks 文档进行排序

find_byreturns单个文档:

#find_by(attrs = {}) {|result| ... } ⇒ Document?

Find the first Document given the conditions.

并且文档没有 order_by 方法。如果你想找到所有带有 bin_id 的文件,那么使用 where:

@bins = Bin.where(bin_id: params[:bin_id]).order_by(:created_at.desc)

请注意,我一路将实例变量切换为复数名称,因为它现在包含(可能)几个 Bins。

问题编辑后,您似乎在此查询

中遗漏了 callbacks
@callbacks = Bin.find_by(bin_id: params[:bin_id]).callbacks.order_by(created_at: "desc")