【问题标题】:is there any way that can offset from specific record when using scope使用范围时有什么方法可以从特定记录中偏移
【发布时间】:2023-03-14 01:41:01
【问题描述】:

我有很多方法可以在特定活动记录之后查找记录。例子是:

def photo_recent
    offsetphoto = Photo.find(params[:id])
    @photos = Photo.recent.where('created_at> ?', offsetphoto.id).limit(10)#recent is a scope using created_at
end

def photo_recent
    offsetphoto = Photo.find(params[:id])
    @photos = Photo.popular.where('like_count > ?', offsetphoto.like_count).limit(10)#popular is a scope using like_count
end

我想知道是否有任何方法可以将其模块化,例如:

@photos = Photo.recent.offset(Photo.find(params[:id])).limit(10)

【问题讨论】:

    标签: sql ruby-on-rails activerecord offset


    【解决方案1】:
    # models/photo.rb
    scope :most_recent_starting_from, -> (photo) { order(created_at: :asc).where('created_at >= ?', photo.created_at) }
    

    示例用法

    photo = Photo.find(123)
    ten_next_created_photos_after_photo = Photo.most_recent_starting_from(photo).limit(10)
    

    【讨论】:

      【解决方案2】:

      您可以编写一个只获取当前 Photo 中的所有内容的范围

      scope :offset_from, -> (photo) { where('id >= ?', photo.id) }
      
      Photo.offset_from(Photo.find(params[:id]))......
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-02
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 2015-01-19
        • 1970-01-01
        相关资源
        最近更新 更多