Sort posts by like count - query not including posts with 0 likes

Controller

@posts = Post.order(likes_count: ‘desc’).page params[:page]

Post model

has_many :likes, dependent: :destroy

has_many :liked_users, through: :likes, source: :user

Likes model

belongs_to :post, counter_cache: :likes_count

It does not sort the posts with 0 likes. For example desc: 0 0 0 5 4 3 Acending: 3 5 5 0 0 0

I’m going to guess that this is an ActiveRecord model. According to your schema, what type is likes_count?

def change add_column :posts, :likes_count, :integer, default: 0, null: false

Post.find_each{ |u| Post.reset_counters(u.id, :likes)}

end

Now it works, the problem was i did not have a default value in my DB, now that I have one it works as intended

1 Like

Yup. I frequently get bitten by trying to sort with nil values. It seems so logical to me that nil is as good as 0, but that’s probably my (thankfully historical) PHP experience talking…

Walter