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



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

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)
# 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)

您可以编写一个范围,该范围只从当前Photo

中获取所有内容
scope :offset_from, -> (photo) { where('id >= ?', photo.id) }
Photo.offset_from(Photo.find(params[:id]))......

最新更新