2009-09-23 34 views
4

我最近分手我的查詢到4個命名的範圍,以便更容易重新排序和分頁,否則始終正常工作現在有問題計算頁數。將分類錯誤與指定的範圍

named_scope :loc, lambda { |id| { :conditions => ['location_id = ?', id ] } } 
    named_scope :datem, lambda { |*args| { :joins => :scannables, :conditions => [ "scannables.bookdate BETWEEN ? and ?", (args[0].to_date || 3.days.from_now), (args[0].to_date+(args[1] || 3)) ], :group => 'scannables.hostel_id', :having => 'SUM(scannables.available) > ' + ((args[1] || 3).to_i-1).to_s } } 
    named_scope :order_by_external_desc, :include => :external_ratings, :order => 'SUM(scannables.available) DESC, external_ratings.rating DESC' 
    named_scope :order_by_external_asc, :include => :external_ratings, :order => 'SUM(scannables.available) DESC, external_ratings.rating ASC' 

使用像這樣用PAGINATE扔在年底...

@location = Place.loc(params[:id]).datem(user_cart.getDate,user_cart.getDays).order_by_external_desc.paginate(:per_page => 15, :page => params[:page]) 

PAGINATE例如將表明,有6頁的各15,但是當你到了4頁,5頁6消失......如果你嘗試直接跳到5或6,他們就不存在。

看着它,我實現了問題將分頁是具有是

[email protected] = Place.loc(params[:id]).datem(user_cart.getDate,user_cart.getDays).order_by_external_desc.size 

c = 78 

然而

[email protected] = Place.loc(params[:id]).datem(user_cart.getDate,user_cart.getDays).order_by_external_desc 

c.size = 56 

對於前者得到生成的SQL是比後者的短約8行並忽略我的SQL HAVING子句,導致它返回更多結果...

有關如何解決此問題的任何想法?

+1

瞎猜:它有助於在'.paginate'之前添加'.all'嗎? – tsherif 2012-04-07 15:57:34

+0

你有答案嗎? – Joerg 2012-05-02 13:24:43

回答

0

當使用group_by/having時 - 就像你在datem中做的那樣named_scope - 不幸的是ActiveRecord的計數錯誤。我不認爲你能做些什麼。我也不確定這是否肯定是ActiveRecord中的一個錯誤 - 或者只是一個在生成SQL的性質使用ActiveRecord時無法正確計算的東西。

無論哪種方式 - 你需要解決這個'錯誤'。

做到這一點的方法是解決在一個單獨的SQL語句中的計數(就是那個給你正確的結果),並將其添加到PAGINATE結果像這樣:

total_entries = Place.count(sql) # or the combinations of named_scopes etc with a .size or whichever one gives you the correct count 

Place.scopes.paginate(:per_page => 15, :page => params[:page], :total_entries => total_entries) # where scopes are all of your named scopes as you have in your examples