Reputation: 6551
I have a pretty basic model called Review (basically just an ID serial and some text columns) and I'm making a simple pagination system for it. The following code:
Review.all(:limit => per_page, :offset => offset, :order => [ :id.asc ])
Returns the correct objects if the offset is 0, but is problematic if offset is anything else. With an offset > 0, the code:
reviews = Review.all(:offset => offset, :limit => per_page);
p reviews
p reviews.count
returns
[#<Review @id=11 @created_at=<not loaded> @rating=<not loaded> @title=<not loaded> @text= <not loaded> @name=<not loaded> @from=<not loaded> @stay_date=<not loaded> @helpful=0 @not_helpful=0 @response=<not loaded>>, #<Review @id=12 @created_at=<not loaded> @rating=<not loaded> @title=<not loaded> @text=<not loaded> @name=<not loaded> @from=<not loaded> @stay_date=<not loaded> @helpful=0 @not_helpful=0 @response=<not loaded>>, #<Review @id=13 @created_at=<not loaded> @rating=<not loaded> @title=<not loaded> @text=<not loaded> @name=<not loaded> @from=<not loaded> @stay_date=<not loaded> @helpful=0 @not_helpful=0 @response=<not loaded>>, #<Review @id=14 @created_at=<not loaded> @rating=<not loaded> @title=<not loaded> @text=<not loaded> @name=<not loaded> @from=<not loaded> @stay_date=<not loaded> @helpful=0 @not_helpful=0 @response=<not loaded>>, #<Review @id=15 @created_at=<not loaded> @rating=<not loaded> @title=<not loaded> @text=<not loaded> @name=<not loaded> @from=<not loaded> @stay_date=<not loaded> @helpful=0 @not_helpful=0 @response=<not loaded>>]
0
How is this? It's finding the objects, but can't count them?
Upvotes: 1
Views: 299
Reputation: 1359
You could convert the lazy list into an array with #to_a
and #count
that (e.g., Review.all(:limit => 10, :offset => 10).to_a.count
).
By the way, there is rather nice syntactic sugar for limit and offset in the spirit of Array
: Review[offset,limit]
.
Complete example:
require 'rubygems'
require 'dm-core'
require 'dm-migrations'
require 'dm-sweatshop' # just to load some fixtures
DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(:default, "sqlite::memory:")
class Review
include DataMapper::Resource
property :id, Serial
property :title, String, :required => true
property :rating, Integer, :min => 1, :max => 10
property :created_at, DateTime, :default => lambda {Time.now}
end
DataMapper.finalize.auto_migrate!
class FixtureHelpers # Just to cache for sweatshop, avoid polluting top-level
@@date_range = (Date.new(2003)..Date.today).to_a
def self.rand_date; @@date_range.choice end
end
Review.fix {{
:title => /\w+/.gen.capitalize,
:rating => (1..10).to_a.choice,
:created_at => FixtureHelpers.rand_date
}}
100.of {Review.gen}
p Review[95,10].to_a.count
# ~ (0.000105) SELECT "id", "title", "rating", "created_at" FROM "reviews" ORDER BY "id" LIMIT 10 OFFSET 95
# => 5
Upvotes: 1