How to sort by created_at column of association in rails? How to sort by created_at column of association in rails? sql sql

How to sort by created_at column of association in rails?


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

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

ought to do it.

One nice trick is to use the rails console when inspecting associations. Specifically, it helps to use the 'to_sql' method on Active Record queries you are performing.

For instance:

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


use this in your post model for set default order:

default_scope { order("created_at DESC") }