【问题标题】:Adding scope to get objects in reverse order of their created time in rails添加范围以在 Rails 中以创建时间的相反顺序获取对象
【发布时间】:2015-04-26 17:18:10
【问题描述】:

我是 Ruby on rails 和编程的新手。 我正在做一个练习,我有一个 Post 模型,我需要向它添加一个新的 scope 以按创建时间的相反顺序检索其对象。

这是我的模型代码:

class Post < ActiveRecord::Base
      has_many :comments
      belongs_to :user 
scope :ordered_by_reverse_order, -> { order('created_at DESC').reverse} 
end

我也试过{reverse('created_at DESC')},都没有用。

【问题讨论】:

    标签: ruby-on-rails ruby model scope


    【解决方案1】:

    试试这个:

    范围:ordered_by_reverse_order,-> { order('created_at ASC') }

    【讨论】:

      【解决方案2】:

      听起来你想要reverse_order(Rails 3+)。

      scope :ordered_by_reverse_order, -> { order(:created_at).reverse_order }
      

      【讨论】:

        【解决方案3】:

        在为 Rails 上的模型定义范围时,我更喜欢使用类方法。 这与您的范围方法完全相同,但我个人认为它更清洁。

        尝试按升序而不是降序排列您的帖子:

        class Post < ActiveRecord::Base
          has_many :comments
          belongs_to :user 
        
          def self.reversed
            order('created_at ASC')
          end 
        end
        
        # ASC
        # Fri, 20 Feb 2015 08:41:26 UTC +00:00
        # Fri, 20 Feb 2015 08:42:25 UTC +00:00
        # Fri, 20 Feb 2015 08:43:53 UTC +00:00
        
        # DESC
        # Fri, 20 Feb 2015 12:43:25 UTC +00:00
        # Fri, 20 Feb 2015 08:44:48 UTC +00:00
        # Fri, 20 Feb 2015 08:43:53 UTC +00:00
        

        执行以下命令应该返回你想要的:

        Post.reversed
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-05-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-05
          相关资源
          最近更新 更多