Rails:将 will

编程入门 行业动态 更新时间:2024-10-24 22:19:56
本文介绍了Rails:将 will_paginate 与复杂的关联查找一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在进行复杂的查找时遇到了 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}"

我想获取在 tag_ids 数组中包含所有标签的所有照片.MySQL 的 IN 通常进行或"搜索,但我需要和".我找到了如何修改 IN 以模仿和"行为 here 并且它在使用 model.find() 时工作​​正常,只要获取的记录数低于我的 :per_page 计数也可以工作.但是如果一定要分页,生成的SQL类似:

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`(...)

这不起作用.其他人已经看到了这个错误,并且能够将他们的 count() 移出查询,但我认为在我的情况下这是不可能的.

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.

有没有更好的方法来进行这种搜索,可以与 will_paginate 一起使用?如果这是唯一的方法,我想我应该研究另一个分页插件?

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?

谢谢!

推荐答案

仅供参考,这是我最终找到的解决方案:

FYI, here's what I finally found to fix this:

@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

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

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.

更多推荐

Rails:将 will

本文发布于:2023-10-24 19:35:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524811.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!