How to sort the created_at association column in rails?

Here are my associations:

Class Post belongs_to :user has_many :favorites, :dependent => :destroy has_many :favoriters, :through => :favorites, :source => :user end Class User has_many :posts has_many :favorites, :dependent => :destroy has_many :favorited, :through => :favorites, :source => :post end Class Favorites belongs_to :user, :post end 

I want to sort my users favorite posts by the created_at column in the Favorites association. However, this type is created by the Post created_at attribute, not the Favorites created_at attribute. How can I sort the Favorites attribute created_at?

  @ posts=@user.favorited.order ('created_at DESC') 
+6
source share
2 answers

You need to specify which table you want to use in the order by clause.

 @posts = @user.favorited.order('posts.created_at DESC') 

must do it.

One nice trick is to use the rail console when checking associations. In particular, it helps to use the "to_sql" method for Active Record queries that you execute.

For instance:

 % bundle exec rails console > u = User.last > u.favorited.order('created_at DESC').to_sql 
+15
source

use this in your post model for a given default order:

 default_scope { order("created_at DESC") } 
+3
source

Source: https://habr.com/ru/post/915698/


All Articles