1

我有一个非常基本的模型,称为 Review(基本上只是一个 ID 序列和一些文本列),我正在为它制作一个简单的分页系统。以下代码:

Review.all(:limit => per_page, :offset => offset, :order => [ :id.asc ])

如果偏移量为 0,则返回正确的对象,但如果偏移量为其他值,则会出现问题。偏移量 > 0 时,代码:

reviews = Review.all(:offset => offset, :limit => per_page);
p reviews
p reviews.count

返回

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

这怎么样?它正在寻找对象,但无法计算它们?

4

1 回答 1

1

#to_a您可以将惰性列表转换为带有和的数组#count(例如,Review.all(:limit => 10, :offset => 10).to_a.count)。

顺便说一句,本着Array:的精神,limit 和 offset 有相当不错的语法糖Review[offset,limit]

完整示例:

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
于 2013-02-25T07:48:36.207 回答