Rails will_paginate在HABTM模型上显示重复项 [英] Rails will_paginate shows duplicates on HABTM models

查看:48
本文介绍了Rails will_paginate在HABTM模型上显示重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将will_paginate用于博客帖子和标签之间的HABTM关系。每当我应用分页时,都会显示重复的帖子,因为Rails中的HABTM不会保持数据库唯一,而是在查询时应用唯一性。

I'm using will_paginate with a HABTM relationship between Blog Posts and Tags. Whenever I apply pagination, I get duplicate posts shown because the HABTM in Rails doesn't keep the database unique, it applies the uniqueness upon making the query.

blog_posts.rb

blog_posts.rb

has_and_belongs_to_many:tags,:uniq => true

tag.rb

has_and_belongs_to_many:blog_posts ,:uniq => true

每个文档用于ActiveRecord,:uniq不会阻止重复的关系被存储,它只会在构建查询时忽略它们。

Per the documentation for ActiveRecord, :uniq does not prevent duplicate relationships being stored, it just ignores them when building the query.

这是问题所在:
tag = Tag.find(1)
tag.blog_posts.count 等于1,但是:
tag.blog_posts.page(nil).count 等于3,并且所有3个都是同一帖子的重复项。正确的行为应该是仅显示1,而不是重复。

Here is the issue: tag = Tag.find(1) tag.blog_posts.count equals 1, but: tag.blog_posts.page(nil).count equals 3, and all 3 are duplicates of the same post. The correct behavior should be to show only 1, not duplicated.

我知道我可以复制此处生成的SQL查询并以这种方式修复,但是似乎不是一个好的解决方案。有人可以帮我解决潜在的问题吗? (尽管我担心这是will_paginate中的错误)

I know I could just copy the SQL queries that are being generated here and fix it that way, but that doesn't seem to be a good solution. Could someone help me fix the underlying problem? (though I'm concerned it's a bug in will_paginate)

编辑:这似乎也是Kaminari的问题。

This appears to be an issue with Kaminari as well.

推荐答案

我认为我之前曾遇到过此问题。尝试将其添加到查询中:

I think I ran into this problem before. Try adding this to your query:

.group("id")

这不是will_paginate中的错误,因为所做的只是获取它提供的数据并在视图中进行分页。解决方案在于您提供的数据。

It's not a bug in will_paginate, because all that does is take the data it gives you and paginates it in the view. The solution lies in the data you provide it.

这篇关于Rails will_paginate在HABTM模型上显示重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆