使用范围时有什么方法可以从特定记录偏移

is there any way that can offset from specific record when using scope

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

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)

您可以编写一个只获取当前 Photo

中的所有内容的作用域
scope :offset_from, -> (photo) { where('id >= ?', photo.id) }

Photo.offset_from(Photo.find(params[:id]))......
# 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)