Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a Rails 3 scope.limit - with an offset?

So I have some posts, and would like to show n..m most recent entries in the sidebar (these numbers being set in a config)

I can get the latest n records easily enough

class Post < ActiveRecord::Base
  default_scope :order => "created_at DESC"
  scope :published, lambda { where("blog_entries.created_at <= ?", Time.zone.now) }
  scope :latest, lambda { |n| published.limit(n) }
end

@posts = Post.latest(6)

But what I'd like is

@posts = Post.published.limit(6, 12)

but this gives wrong number of arguments, so is there any way in AR? Right now I'm playing with will_paginate, but it seems hacky to use it for this.

like image 468
sbeam Avatar asked Feb 17 '11 02:02

sbeam


1 Answers

Ok, so the answer is, I think:

@posts = Post.published.limit(6).offset(5)

It will retrieve 6 posts, starting from the sixth.


edit2: About the limit([6, 12]), I find that strange:

attr_accessor :limit_value

def limit(value)
  relation = clone
  relation.limit_value = value
  relation
end


def build_arel
    ...
    arel.take(connection.sanitize_limit(@limit_value)) if @limit_value
    ...
end


def sanitize_limit(limit)
    if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral)
      limit
    elsif limit.to_s =~ /,/
      Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',')
    else
      Integer(limit)
    end
  end

So I don't really see how it works with an array. But I obviously missed something. Do you see what?

like image 103
Robin Avatar answered Sep 24 '22 04:09

Robin