簡體   English   中英

將will_paginate與多個模型一起使用(Rails)

[英]Using will_paginate with multiple models (Rails)

很確定我在這里遺漏了一些非常簡單的東西:

我正在嘗試顯示一系列包含兩個不同模型實例的頁面 - 配置文件和組。 我需要按名稱屬性排序。 我可以為每個模型選擇所有實例,然后對它們進行排序和分頁,但這感覺很邋and且效率低下。

我正在使用mislav-will_paginate,並想知道是否有更好的方法來實現這一目標? 就像是:

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

會是理想的!

好問題,我遇到過幾次相同的問題。 每次,我通過編寫基於sql聯合的自己的sql查詢來結束它(它與sqlite和mysql一起正常工作)。 然后,您可以通過傳遞結果來使用will paginate( 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}")

它是否過度使用? 也許,但你得到的查詢數量最少,結果也是一致的。

希望能幫助到你。

注意:如果從http參數獲得偏移值,則應使用sanitize_sql_for_conditions(即:sql injection ....)

你可以近距離做一些事情:

@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有什么好處。

在我的上一個項目中我遇到了一個問題,我不得不在我的搜索功能中對單個分頁的多個模型進行分頁。 它應該以第一個模型應該首先出現的方式工作,第一個模型的結果第二個模型應該繼續結果而第三個等等作為一個單一的搜索提要,就像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存儲庫,如果每個人都確認它正常工作我將fork並將其提交到庫。 https://github.com/mislav/will_paginate/issues/351

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM