[英]How to sort by created_at column of association in rails?
這是我的協會:
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')
您需要在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
在您的帖子模型中使用此設置默認順序:
default_scope { order("created_at DESC") }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.