1

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.

John
  • 3,430
  • 2
  • 31
  • 44

1 Answers1

6

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.

Ultimation
  • 1,059
  • 9
  • 18
  • 2
    This works! But I disagree, I think it is a bug. will_paginate is ignoring the specifications of ActiveRecord. Things work without will_paginate, they don't work with it because it changes the normal ActiveRecord SQL query, and you have to go out of your way to make things work. Thanks a lot for the solution!!! – John Jul 31 '12 at 18:51
  • Yes thanks Ultimation - agree that this could be considered a bug or at least an improvement for will_paginate – Brett Jul 30 '16 at 08:31