Rails will_paginate shows duplicates on HABTM models

半城伤御伤魂 提交于 2019-12-11 11:39:26

问题


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

has_and_belongs_to_many :tags, :uniq => true

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.

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.

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)

Edit: This appears to be an issue with Kaminari as well.


回答1:


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. The solution lies in the data you provide it.



来源:https://stackoverflow.com/questions/11729816/rails-will-paginate-shows-duplicates-on-habtm-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!