Rails & Kaminari: Pagination showing duplicate results
<p>I have a rails app using Kaminari for pagination. For some reason, on some pages, some of the last results of the last page are carried over to the first results of the next page.</p>

<p>Here's my controller:</p>

<pre><code> def available
    trailers = Trailer.most_recent.released.order("movies.imdb_rating desc").where("movies.imdb_rating IS NOT NULL")
    @trailers = trailers.page(params[:page]).per(18)
end
</code></pre>

<p>Scopes in the Trailer model:</p>

<pre><code> scope :most_recent, -&gt; {
    where('NOT EXISTS(SELECT 1 FROM trailers b2 WHERE b2.movie_id = trailers.movie_id AND trailers.is_short_trailer = FALSE AND
    b2.is_short_trailer = FALSE
    AND (b2.published_at &gt; trailers.published_at OR b2.published_at = trailers.published_at AND b2.id &lt; trailers.id))').
    where(show: true).
    where(is_short_trailer: false)
  }

  # gets all trailers that have at least one release
  scope :released, -&gt; { 
    joins(movie: :releases).where("movies.release_date &gt; ?", 25.years.ago)
  }
</code></pre>

<p>And the view:</p>

<pre><code>&lt;div class="trailers-container"&gt;
  &lt;%= render @trailers %&gt;
&lt;/div&gt;


&lt;div class="pagination"&gt;
  &lt;%= link_to_next_page(@trailers, 'Next') %&gt;
&lt;/div&gt;
</code></pre>

<p>So when I click on the 'Next' page, sometimes it's fine, but sometimes I will see duplicate trailers (actual duplicates, I checked the IDs). </p>

<p>What am I doing wrong?</p>