Gintron
(Gintron)
December 7, 2021, 9:56pm
1
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
muyiwa
(Muyiwa Olu)
December 8, 2021, 12:24am
2
I’m going to guess that this is an ActiveRecord model. According to your schema, what type is likes_count
?
Gintron
(Gintron)
December 8, 2021, 9:11am
3
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