2009-07-07 37 views
7

敢肯定,我失去了在這裏很簡單的東西:有多個型號(Rails)的使用will_paginate

我想展示了一系列含有兩種不同型號的情況下頁 - 配置文件和組。我需要他們按他們的名字屬性排序。我可以爲每個模型選擇所有的實例,然後對它們進行分類和分頁,但是這會讓人覺得草率和低效。

我正在使用mislav-will_paginate,並想知道是否有更好的方法來實現它?例如:

[Profile, Group].paginate(...) 

會是理想的!

回答

6

好問題,我遇到了同樣的問題幾次。每一次,我都通過編寫基於sql工會的自己的sql查詢來結束它(它對sqlite和mysql工作正常)。然後,您可以通過傳遞結果來使用將分頁(http://www.pathf.com/blogs/2008/06/how-to-use-will_paginate-with-non-activerecord-collectionarray/)。不要忘記執行查詢來統計所有行。

一些代碼行(未測試)

my_query = "(select posts.title from posts) UNIONS (select profiles.name from profiles)" 
total_entries = ActiveRecord::Base.connection.execute("select count(*) as count from (#{my_query})").first['count'].to_i 

results = ActiveRecord::Base.connection.select_rows("select * from (#{my_query}) limit #{limit} offset #{offset}") 

難道overkilled?也許,但你有最少的查詢和結果是一致的。

希望它有幫助。

注意:如果你從一個http PARAM獲得偏移值,你應該使用sanitize_sql_for_conditions(即:SQL注入....)

0

您是否嘗試過使用自己的paginators顯示兩組不同的結果並通過AJAX更新它們?這不完全是你想要的,但結果是相似的。

+0

不幸的是,這不會削減它 - 我需要有兩組實例在一起。 – Codebeef 2009-07-07 14:08:45

1

你可以親近做這樣的事情:

@profiles, @groups = [Profile, Group].map do |clazz| 
    clazz.paginate(:page => params[clazz.to_s.downcase + "_page"], :order => 'name') 
end 

那麼就會使用分頁頁面參數profile_pagegroup_page。你可以得到will_paginate呼籲在視圖中使用,使用正確的頁面:

<%= will_paginate @profiles, :page_param => 'profile_page' %> 
.... 
<%= will_paginate @groups, :page_param => 'group_page' %> 

不過,我不知道有過建立@groups@profiles單獨一個巨大的好處。

1
在我的最後一個項目,我堅持了一個問題

,我不得不多分頁我的搜索功能中具有單個分頁的模型。 它應該以第一個模型應該首先出現的方式工作,當第一個模型的結果和第二個模型的結果應該繼續結果,第三個等等作爲一個單一搜索源時,就像facebook源一樣。 這是我創造了這樣做的功能

def multi_paginate(models, page, per_page) 

    WillPaginate::Collection.create(page, per_page) do |pager| 

    # set total entries 
    pager.total_entries = 0 
    counts = [0] 
    offsets = [] 
    for model in models 
      pager.total_entries += model.count 
      counts << model.count 
      offset = pager.offset-(offsets[-1] || 0) 
      offset = offset>model.count ? model.count : offset 
      offsets << (offset<0 ? 0 : offset) 
    end 

    result = [] 
    for i in 0...models.count 
      result += models[i].limit(pager.per_page-result.length).offset(offsets[i]).to_a 
    end 

    pager.replace(result) 
    end 

end 

嘗試,讓我知道,如果你有任何問題,它的功能,我還張貼作爲一個問題will_paginate庫,如果每個人都證實,它正常工作我會分叉並將其提交給圖書館。 https://github.com/mislav/will_paginate/issues/351