Ruby on rails 强制ActiveRecord计数不同(使用Kaminari)
我使用Kaminari对一个查询的结果进行分页,在这个查询中我选择了不同的记录。考虑下面的控制器代码:Ruby on rails 强制ActiveRecord计数不同(使用Kaminari),ruby-on-rails,ruby-on-rails-3,activerecord,kaminari,Ruby On Rails,Ruby On Rails 3,Activerecord,Kaminari,我使用Kaminari对一个查询的结果进行分页,在这个查询中我选择了不同的记录。考虑下面的控制器代码: @things = Thing.joins... # create a complex query that produces duplicate results # I want to select distinct results: this produces the correct results @things = @things.select("DISTINCT things.*"
@things = Thing.joins... # create a complex query that produces duplicate results
# I want to select distinct results: this produces the correct results
@things = @things.select("DISTINCT things.*")
# when Kaminari calls count, it will run "SELECT COUNT(*)", instead of
# "SELECT COUNT(DISTINCT things.*)" we will get the wrong count and extra pages
@things = @things.page(params[:page]).per(10)
我能想到的最好的解决方案是传递:distinct=>true to count,如中,这被Kaminari的开发人员拒绝了。讨论潜在的问题。这是一个冒犯性的要求
是否有任何解决方法可以为Kaminari提供正确的计数,而不需要修补Kaminari?谢谢
更新:
使用名为count的范围是一个很好的建议,但在ActiveRecord::Relation上调用时不起作用。在我的模型类上调用时,它可以工作,但这没有帮助。
我建议在模型上设置一个范围 但这可能会使事情变得混乱,因此您需要小心 范围:计数,选择不同的事物*
有关详细信息,请参阅以下url 但是,他们在Rails 3.1.0上失败了 对于Rails 3.1.0,为_distinct.rb创建Rails.root/initializers/kaminari_。 并使用以下代码
module Kaminari
module ActiveRecordRelationMethods
extend ActiveSupport::Concern
module InstanceMethods
def total_count #:nodoc:
if distinct_column_name.nil?
c = except(:offset, :limit).count
else
c = except(:offset, :limit).count(distinct_column_name, :distinct => true)
end
# .group returns an OrderdHash that responds to #count
c.respond_to?(:count) ? c.count : c
end
# Get the column name used in distinct query.
# This could have been set on the Model class, or the ActiveRecord::Relation
def distinct_column_name
@distinct_column || distinct_column
end
end
end
end
module Kaminari
module ConfigurationMethods
extend ActiveSupport::Concern
module ClassMethods
# Set the name of the column to use during .count()
# Setting this will cause call to count to use: count(:id, :distinct => true) for all the Models paged queries.
# Example:
# class User < ActiveRecord::Base
# use_distinct :id
# end
def use_distinct(column)
@distinct_column = column
end
# Returns the distinct column name set on the Model, or nil if not using distinct
def distinct_column
@distinct_column
end
end
end
end
module Kaminari
module PageScopeMethods
extend ActiveSupport::Concern
module InstanceMethods
# Set the name of the column to use during .count()
# Setting this will cause call to count to use: count(:id, :distinct => true)
# Example: User.page(3).per(5).use_distinct(:id)
def use_distinct(column)
@distinct_column = column
self
end
end
end
end
这应该不仅仅是一个注释吗?是的,如果OP要在模型上定义一个作用域并将其命名为count,那么他们将能够控制库在尝试从模型中获取计数时所做的操作。继续提供详细信息,这样就可以了:答案应该是明确的。否则,以注释的形式给出提示。您的意思是创建一个名为count的范围,该范围使用:distinct=>true调用real count方法吗?我试过了,但没有成功。如果我能让它工作的话,那将是一个很好的解决方案。尝试一个直接向上的范围,而不是别名。这可能会有所不同。