简体   繁体   English

Rails will_paginate在HABTM模型上显示重复项

[英]Rails will_paginate shows duplicates on HABTM models

I'm using will_paginate with a HABTM relationship between Blog Posts and Tags. 我正在将will_paginate与Blog帖子和标签之间的HABTM关系配合使用。 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. 每当我应用分页时,都会显示重复的帖子,因为Rails中的HABTM不会保持数据库唯一,而是在进行查询时应用唯一性。

blog_posts.rb blog_posts.rb

has_and_belongs_to_many :tags, :uniq => true

tag.rb tag.rb

has_and_belongs_to_many :blog_posts, :uniq => true

Per the documentation for ActiveRecord, :uniq does not prevent duplicate relationships being stored, it just ignores them when building the query. 根据ActiveRecord的文档 ,:uniq不会阻止重复的关系被存储,它只会在构建查询时忽略它们。

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. 这是问题所在: tag = Tag.find(1) tag.blog_posts.count等于1,但是: tag.blog_posts.page(nil).count等于3,并且所有3个都是同一帖子的重复项。 The correct behavior should be to show only 1, not duplicated. 正确的行为应该是仅显示1,而不是重复。

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. 我知道我可以复制此处生成的SQL查询并以这种方式解决,但这似乎不是一个好的解决方案。 Could someone help me fix the underlying problem? 有人可以帮我解决潜在的问题吗? (though I'm concerned it's a bug in will_paginate) (尽管我担心这是will_paginate中的错误)

Edit: This appears to be an issue with Kaminari as well. 编辑:这似乎也是Kaminari的问题。

I think I ran into this problem before. 我想我曾经遇到过这个问题。 Try adding this to your query: 尝试将其添加到您的查询中:

.group("id")

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. 这不是will_paginate中的错误,因为所有要做的就是获取它提供的数据并在视图中进行分页。 The solution lies in the data you provide it. 解决方案在于您提供的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM