【问题标题】:How to sort by created_at column of association in rails?如何按rails中关联的created_at列排序?
【发布时间】:2012-05-14 16:07:08
【问题描述】:

这是我的联想:

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 属性排序的,而不是 Favorites created_at 属性。如何按收藏夹 created_at 属性排序?

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

【问题讨论】:

  • 你能重新表述你的问题吗?

标签: sql ruby-on-rails activerecord


【解决方案1】:

您需要在 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

【讨论】:

  • 太好了,这行得通。但在我的情况下,它的 @posts = @user.favorited.order('favorites.created_at DESC') 以便它们按收藏夹 created_at 属性排序。感谢您的建议。
【解决方案2】:

在你的帖子模型中使用它来设置默认顺序:

default_scope { order("created_at DESC") }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2017-04-05
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多