Im using the will_paginate gem and rails 3.2.3.
Im trying to display all the posts that have certain tags ordered by the latest post so I use this:
@posts = Post.find_by_post_type_label(session[:current_post_type],@selected_labels)
.paginate(:page => params[:page], :order => "comments.created_at DESC").all
but it returns the posts out of order. Each page will be sorted, but the second page will have posts that should have been on the first one.
Example:
Post.find_by_post_type_label(1,[])
returns posts [1,2,3,4,5,6,7,8,9,10] with each ones latest comment being that many months ago. The sql it generates is:
SELECT `posts`.* FROM `posts` WHERE `post`.`post_type_id` = 1
and
SELECT `comments`.* FROM `comments` WHERE `comments`.`post_id` IN ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ) ORDER BY created_at DESC
If I order it, and limit it though, like:
Post.find_by_post_type_label(1,[]).order(comments.created_at DESC).limit(5)
which is how the will_paginate does it, it returns posts 2,3,4,5,7
after generating this:
SELECT DISTINCT `post`.id FROM `posts` LEFT OUTER JOIN
`comments` ON `comments`.`post_id` = `post`.`id` WHERE
`post`.`post_type_id` = 1 ORDER BY posts.created_at DESC LIMIT 5
and
SELECT `post`.`id` AS t0_r0, `post`.`user_id` AS t0_r1, `post`.`name` AS
t0_r2, `post`.`image_id` AS t0_r3, `post`.`post_type_id` AS t0_r4,
`post`.`description` AS t0_r5, `post`.`featured` AS t0_r6, `post`.`approved`
AS t0_r7, `comment`.`id` AS t1_r0, `comments`.`post_id` AS t1_r1,
`comments`.`image_id` AS t1_r2, `comments`.`edits` AS t1_r3,
`comments`.`color` AS t1_r4, `comments`.`min_reputation` AS t1_r5,
`comments`.`created_at` AS t1_r6, `comments`.`updated_at` AS t1_r7 FROM
`post` LEFT OUTER JOIN `comments` ON `comments`.`post_id` =
`post`.`id` WHERE `post`.`post_type_id` = 1 AND `post`.`id` IN (2, 3,
4, 5, 7) ORDER BY comments.created_at DESC
It is clearly limiting before it is ordering, but I cant figure out how to change that.
Any help would be appreciated
Edit 1
The relationships are like so:
Class Post
belongs_to :user
belongs_to :post_type
has_many :comments, dependent: :destroy, order: 'created_at DESC'
has_and_belongs_to_many :labels
Class Comment
belongs_to :post
belongs_to :user
Comments are the only ones with timestamps in the database. The first comment holds the created at time for the post.
Winded up using this sql in a find_by_sql