Rails:使用 will_paginate 进行复杂的关联查找
我在进行复杂查找时遇到 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 一起使用?如果这是执行此操作的唯一方法,我想我应该研究另一个分页插件?
谢谢!
I'm encountering a problem with will_paginate while doing a complex find.
: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}"
I want to fetch all the photos who have all the tags in the tag_ids array. MySQL's IN usually does "or" searches, but I need "and". I found how to modify IN to mimic "and" behavior here and it works fine when using model.find(), also works as long as the number of records fetched is lower than my :per_page count. But if it has to paginated, the SQL that is generated is similar to:
SELECT count(*) AS count_all, photos.id HAVING COUNT(DISTINCT tags.id) = 1 AS photos_id_having_count_distinct_tags_id_1 FROM `photos`(...)
which doesn't work. Other have seen this bug and were able to move their count() out of the query, but I don't think that's possible in my case.
Is there a better way to do this search that might work with will_paginate? If its the only way to do this, I guess I should look into another pagination plugin?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅供参考,这是我最终发现解决此问题的方法:
您必须使用页码作为偏移量并使用标签进行连接查询来手动构建分页集。有点笨重。
FYI, here's what I finally found to fix this:
You have to manually construct the paginated set using the page number as an offset and using the tags to make a join query. Kinda clunky.
我对此的第一次尝试(抱歉现在没有时间测试它......如果我这样做就会更新)将类似于以下内容(添加 :select 并更改 :group):
My first stab at this (sorry don't have time to test it right now... will update if I do) would be something like the following (added the :select and changed the :group):