我有一个名为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
这是怎么回事?它找到了对象,但无法计算它们?
答案 0 :(得分:1)
您可以将惰性列表转换为#to_a
和#count
的数组(例如Review.all(:limit => 10, :offset => 10).to_a.count
)。
顺便说一下,Array
: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