簡體   English   中英

Rails:將will_paginate與復雜的關聯一起使用find

[英]Rails: Using will_paginate with a complex association find

我在進行復雜的查找時遇到了will_paginate的問題。

:photo  has_many   :tags,   :through => :tagships
:item   has_many   :photos
:photo  belongs_to :item


@photos = @item.photos.paginate :page => params[:page],
                                :per_page => 200,
                                :conditions => [ 'tags.id IN (?)', tag_ids],
                                :order => 'created_at DESC',
                                :joins => :tags,
                                :group => "photos.id HAVING COUNT(DISTINCT tags.id) = #{tag_count}"

我想獲取所有在tag_ids數組中具有所有標簽的照片。 MySQL的IN通常會執行“或”搜索,但我需要“和”。 我發現如何在此處修改IN以模仿“和”行為並且在使用model.find()時效果很好,只要獲取的記錄數小於我的:per_page計數,它也可以工作。 但是,如果必須分頁,則生成的SQL類似於:

SELECT count(*) AS count_all, photos.id HAVING COUNT(DISTINCT tags.id) = 1 AS photos_id_having_count_distinct_tags_id_1 FROM `photos`(...)

這不起作用。 其他人已經看到了該錯誤,並能夠將其count()移出查詢,但是對於我而言,這是不可能的。

有沒有更好的方法來進行可能與will_paginate一起使用的搜索? 如果這是唯一的方法,我想我應該看看另一個分頁插件嗎?

謝謝!

僅供參考,這是我終於找到的解決方法:

@photos = WillPaginate::Collection.create(current_page, per_page) do |pager|
    result = @item.photos.find :all, :conditions => [ 'tags.id IN (?)', tag_ids] ,:order => 'created_at DESC', :joins => :tags, :group => "photos.id HAVING COUNT(DISTINCT tags.id) = #{@tags.count}", :limit => pager.per_page, :offset => pager.offset
    pager.replace(result)

    unless pager.total_entries
      pager.total_entries = @item.photos.find(:all, :conditions => [ 'tags.id IN (?)', tag_ids] ,:order => 'created_at DESC', :joins => :tags, :group => "photos.id HAVING COUNT(DISTINCT tags.id) = #{@tags.count}").count
    end
  end

您必須使用頁碼作為偏移量並使用標簽進行聯接查詢來手動構造分頁集。 有點笨拙。

我的第一個選項(對不起,現在沒有時間進行測試...如果我這樣做,將會更新)將類似於以下內容(添加了:select並更改了:group):

@photos = @item.photos.paginate :page => params[:page],
                                :per_page => 200,
                                :select => "photos.*, COUNT(DISTINCT tags.id) AS tag_count",
                                :conditions => [ 'tags.id IN (?)', tag_ids ],
                                :order => 'created_at DESC',
                                :joins => :tags,
                                :group => "photos.id HAVING tag_count = #{tag_count}"

暫無
暫無

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

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