如何在rails中按关联的created_at列进行排序?

时间:2012-05-14 16:07:08

标签: sql ruby-on-rails activerecord

以下是我的协会:

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

我想按收藏夹关联的created_at列对用户最喜欢的帖子进行排序。但是,这可以通过Post created_at属性进行排序,而不是收藏夹created_at属性。如何按收藏夹created_at属性排序?

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

2 个答案:

答案 0 :(得分:16)

您需要在order by子句中指定要使用的表。

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

应该这样做。

一个很好的技巧是在检查关联时使用rails控制台。具体来说,在正在执行的Active Record查询中使用'to_sql'方法很有帮助。

例如:

% bundle exec rails console

> u = User.last
> u.favorited.order('created_at DESC').to_sql

答案 1 :(得分:4)

在您的帖子模型中使用此设置默认顺序:

default_scope { order("created_at DESC") }