为什么在调用同一页面时,will_paginate#paginate会包含不同的对象?

时间:2013-12-11 17:41:02

标签: ruby-on-rails activerecord will-paginate

在调用同一页面后,会返回不同的ID。

Product.paginate(per_page: 15, page: 100).pluck(:id)
   (1.2ms)  SELECT "products"."id" FROM "products" LIMIT 15 OFFSET 1485
=> [37990, 37991, 37992, 37993, 37994, 37995, 37996, 37997, 37998, 37999, 38000, 38001, 38002, 38003, 38004]

Product.paginate(per_page: 15, page: 100).pluck(:id)
   (0.7ms)  SELECT "products"."id" FROM "products" LIMIT 15 OFFSET 1500
=> [38799, 38800, 38801, 38802, 38803, 38804, 38805, 38806, 38807, 38808, 38809, 38810, 38811, 38812, 38813]

Product.paginate(per_page: 15, page:100).pluck(:id)
   (3.0ms)  SELECT "products"."id" FROM "products" LIMIT 15 OFFSET 1485
=> [24513, 24514, 33230, 18489, 33509, 33510, 33511, 33512, 33513, 33514, 34250, 33515, 33516, 33517, 33518]

我的产品型号:

class Product < ActiveRecord::Base
  attr_accessible  :brand_id, :description, :name, :db_ref, :packages_attributes, :photos_attributes, :published, :alias

  # Relations
  has_many :photos
  accepts_nested_attributes_for :photos
  has_many :cart_items
  has_many :packages, inverse_of: :product
  accepts_nested_attributes_for :packages, allow_destroy: true
  has_many :prices, :through => :packages
  has_many :group_assignments, as: :groupable
  has_many :groups, through: :group_assignments
  belongs_to :brand
  belongs_to :business

  # Callbacks
  before_validation :inherit_business_id
  before_create :set_default_alias

  # Validations
  validates_presence_of :name
  validates_presence_of :business
  validates_uniqueness_of :name, scope: [:brand_id, :business_id, :published]
end

1 个答案:

答案 0 :(得分:2)

尝试添加排序,看看是否能解决问题:

Product.order(:id).paginate(per_page: 15, page: 100).pluck(:id)

正在发生的事情是无法保证从数据库返回结果的顺序,因此它们将以未知顺序返回。通过添加特定订单,您可以保证每次都返回相同的订单。