【问题标题】:My rails model won't order entries properly, why?我的 rails 模型无法正确排序条目,为什么?
【发布时间】:2011-10-22 03:04:42
【问题描述】:

我有一个具有以下范围的 rails 模型:

 default_scope order('created_at ASC')
 scope :published, order('created_at DESC').where(:draft=>false)

很遗憾,发布的范围不会按降序排列条目。

我写错了这个范围吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 scope


    【解决方案1】:

    我相信:published 范围不会覆盖默认排序,除非您使用reorder

    http://guides.rubyonrails.org/active_record_querying.html#reorder

    试试

    scope :published, where(:draft=>false).reorder('created_at DESC')
    

    【讨论】:

      【解决方案2】:

      您的默认作用域仍会触发;你可以.reorder,显式获取Foo.unscoped.published,或者使用with_exclusive_scope

      请参阅this SO question 了解更多详情,包括另一个包含更多信息的 SO 问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-01
        相关资源
        最近更新 更多