I want to keep the rails associated with sorting.

Asked 1 years ago, Updated 1 years ago, 71 views

Post has_many Comment

@post=Post.find(xxx)
@post.comments=post.comments.custom_order
@post.comments

@post.comments I'd like to sort the comments, what should I do?

ruby-on-rails rails-activerecord

2022-09-30 21:29

1 Answers

has_many with scope.

has_many:comments, ->{order('created_at DESC')}

as
post=Post.find(1)
puts post.comments.to_sql
# SELECT "comments".* FROM "comments" WHERE "comments". "post_id" = 1ORDER BY created_at DESC


2022-09-30 21:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.