Rails 如果给嵌入 (embed) 模型做默认排序?

bindiry · 2011年12月08日 · 最后由 xranthoar 回复于 2012年05月21日 · 2936 次阅读

以下是两个模式,Device 嵌入到 Brand 中,同时在两个模型中都设置了 default_scope 当我在 controller 中 Brand.all 时,取出的数据 Brand 是正确的排序,Brand.devices 的却没有生效,我该怎么给 Brand 下的 Device 做默认排序?

class Brand
  include Mongoid::Document
  field :name
  embeds_many :devices
  default_scope asc(:name)
end
class Device
  include Mongoid::Document
  field :name
  embedded_in :brand
  default_scope asc(:name)
end

这个还没试过,你试试给 embeds_many :devices 加上排序参数呢

embeds_many :devices, desc(:name)

#1 楼 @huacnlee 谢谢回复,试了一下,报错:can't convert Mongoid::Criteria into Hash。

google 了一下,也没有找到一个可行的解决办法,悲剧了。。

似乎 mongodb 本身就不支持。。。囧

#3 楼 @bindiry 我倒是几乎没有给 has_many 这种一对多关联设置默认排序的情况

#4 楼 @huacnlee 哦,我这个用的是 embeds_many,主要是想在一个场景中,把品牌和型号全列出来,当然型号想从旧到新的排下序。

还是放着,做着别的功能先,后面慢慢深入了解下。

@bindiry @huacnlee 可以写 default_scope 的吧?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号