0

我有一个带有评分列(整数)的帖子模型的 Rails 应用程序(postgres + postGIS)。如果我进入控制台并执行以下操作:

Post.order("rating DESC").map(&:id)
=> [9, 15, 19, 6, 17, 5, 4, 16, 1, 3, 13, 20, 14, 10, 8, 12, 7, 2, 18, 11]

但是,如果我尝试通过限制和偏移一次循环遍历那些,我会得到奇怪的结果。

Post.order("rating DESC").limit(1).offset(0)
=> [#<Post id: 5, body: "Hi", rating: 4, location: #<RGeo::Geographic::SphericalPointImpl:0x81bb34c0 "POINT (-118.495 34.017)">, user_id: 8, created_at: "2012-07-25 22:43:41", updated_at: "2012-07-25 22:43:41">]

为什么那个帖子是#5?应该是#9。无论如何,当我应用偏移量时,它会变得更加古怪。

>Post.order("rating DESC").limit(1).offset(1)
=> [#<Post id: 5, body: "Hi", rating: 4, location: #<RGeo::Geographic::SphericalPointImpl:0x81bb34c0 "POINT (-118.495 34.017)">, user_id: 8, created_at: "2012-07-25 22:43:41", updated_at: "2012-07-25 22:43:41">]

>Post.order("rating DESC").limit(1).offset(2)
=> [#<Post id: 5, body: "Hi", rating: 4, location: #<RGeo::Geographic::SphericalPointImpl:0x81bb34c0 "POINT (-118.495 34.017)">, user_id: 8, created_at: "2012-07-25 22:43:41", updated_at: "2012-07-25 22:43:41">]

>Post.order("rating DESC").limit(1).offset(3)
=> [#<Post id: 5, body: "Hi", rating: 4, location: #<RGeo::Geographic::SphericalPointImpl:0x81bb34c0 "POINT (-118.495 34.017)">, user_id: 8, created_at: "2012-07-25 22:43:41", updated_at: "2012-07-25 22:43:41">]

>Post.order("rating DESC").limit(1).offset(4)
=> [#<Post id: 15, body: "I luv coffee", rating: 4, flagged: 0, location: #<RGeo::Geographic::SphericalPointImpl:0x82260df4 "POINT (-118.495 34.017)">, user_id: 1, created_at: "2012-07-25 22:43:41", updated_at: "2012-07-25 22:43:41">]
4

1 回答 1

3

你注意到rating你展示的唯一结果是 4 吗?您在rating没有辅助排序键的情况下进行排序,因此无法保证将出现什么顺序关系,甚至无法保证在两个不同的调用中关系会以相同的方式排序。

尝试在您的order:

Post.order('rating DESC, id')

然后包含rating在您正在查看的内容中:

Post.order('rating desc, id').select('id, rating').map { |p| [ p.id, p.rating ] }
Post.order('rating desc, id').select('id, rating').limit(1).offset(3).map { |p| [ p.id, p.rating ] }
#...

这应该会给你合理和一致的结果。

于 2012-07-26T20:35:23.420 回答