gpt4 book ai didi

ruby-on-rails - rails : Using will_paginate with a complex association find

转载 作者:行者123 更新时间:2023-12-04 19:21:44 25 4
gpt4 key购买 nike

我在进行复杂的查找时遇到了 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 以模仿“和”行为 here它在使用 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

您必须使用页码作为偏移量并使用标签来手动构建分页集以进行连接查询。有点笨重。

关于ruby-on-rails - rails : Using will_paginate with a complex association find,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2868484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com