List most likes records with active record in rails
@most_likes_posts = Post.joins("LEFT JOIN likes on likes.likeable_id = posts.id and likes.likeable_type = 'Post' and likes.liker_type = 'User'").group('posts.id').select('posts.*','count(likes.likeable_id) as likes_count').select('posts.*','count(likes.likeable_id) as likes_count').sort_by(&:likes_count).last(20) @lessons = Lesson.joins('INNER JOIN views ON lessons.id = views.viewable_id') .joins('LEFT OUTER JOIN likes ON lessons.id = likes.likeable_id') .select('lessons.*, sum(views.count) AS views_sum, count(likes.likeable_id) AS likes_count') .group('lessons.id') .order('sum(views.count) DESC').paginate(page: params[:page], per_page: 40) List lessons which has at least 1 post: ...