我在我的Rails 4项目中使用了will_paginate gem。当我查看从调用paginate()
返回的对象的祖先时,我以为我会在祖先列表中看到与will_paginate相关的内容,例如,可能是WillPaginate::Collection
,但我看不到类似的东西这个。如果will_paginate没有出现在祖先树的任何地方,我很困惑我的对象如何获得current_page
和total_pages
等方法。
例如:
location = Location.first
reviews = location.location_reviews.paginate(page: 1, per_page: 5)
reviews.next_page # => 2
reviews.total_pages # => 16
reviews.total_entires # => 80
但是,reviews.ancestors
的输出是:
[LocationReview(id: integer, title: string), LocationReview::GeneratedAssociationMethods, #<#<Class:0x007fd6623bec38>:0x007fd6623beda0>, ActiveRecord::Base, GlobalID::Identification, ActiveRecord::Store, ActiveRecord::Serialization, ActiveModel::Serializers::Xml, ActiveModel::Serializers::JSON, ActiveModel::Serialization, ActiveRecord::Reflection, ActiveRecord::NoTouching, ActiveRecord::Transactions, ActiveRecord::Aggregations, ActiveRecord::NestedAttributes, ActiveRecord::AutosaveAssociation, ActiveModel::SecurePassword, ActiveRecord::Associations, ActiveRecord::Timestamp, ActiveModel::Validations::Callbacks, ActiveRecord::Callbacks, ActiveRecord::AttributeMethods::Serialization, ActiveRecord::AttributeMethods::Dirty, ActiveModel::Dirty, ActiveRecord::AttributeMethods::TimeZoneConversion, ActiveRecord::AttributeMethods::PrimaryKey, ActiveRecord::AttributeMethods::Query, ActiveRecord::AttributeMethods::BeforeTypeCast, ActiveRecord::AttributeMethods::Write, ActiveRecord::AttributeMethods::Read, ActiveRecord::Base::GeneratedAssociationMethods, #<#<Class:0x007fd661d14e28>:0x007fd661d14ef0>, ActiveRecord::AttributeMethods, ActiveModel::AttributeMethods, ActiveRecord::Locking::Pessimistic, ActiveRecord::Locking::Optimistic, ActiveRecord::AttributeDecorators, ActiveRecord::Attributes, ActiveRecord::CounterCache, ActiveRecord::Validations, ActiveModel::Validations::HelperMethods, ActiveSupport::Callbacks, ActiveModel::Validations, ActiveRecord::Integration, ActiveModel::Conversion, ActiveRecord::AttributeAssignment, ActiveModel::ForbiddenAttributesProtection, ActiveRecord::Sanitization, ActiveRecord::Scoping::Named, ActiveRecord::Scoping::Default, ActiveRecord::Scoping, ActiveRecord::Inheritance, ActiveRecord::ModelSchema, ActiveRecord::ReadonlyAttributes, ActiveRecord::Persistence, ActiveRecord::Core, Object, ActiveSupport::Dependencies::Loadable, PP::ObjectMixin, JSON::Ext::Generator::GeneratorMethods::Object, Kernel, BasicObject]
为什么在这个输出中没有与will_paginate相关的类?
答案 0 :(得分:0)
您正在.paginate
上调用location.location_reviews
方法,这是此处的集合。根据{{1}}方法的源代码的this line和this line,似乎paginate
方法在应用选项后返回原始集合(例如paginate
)在那。
因此,我认为per_page
将返回location.location_reviews.paginate(page: 1, per_page: 5)
类对象的正常行为。
location.location_reviews.class
将返回https://github.com/mislav/will_paginate/blob/74a6cd0197072903cd8b83744133744ff4b4c046/lib/will_paginate/array.rb#L30将返回的内容,并在此处定义paginate
方法:https://github.com/mislav/will_paginate/blob/74a6cd0197072903cd8b83744133744ff4b4c046/lib/will_paginate/collection.rb#L112-L134
它返回原始集合类型对象。这证明您看到的行为是正确的。