简体   繁体   中英

Rails will_paginate shows duplicates on HABTM models

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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