2012-05-14 2 views
6

여기 내 협회입니다레일스에서 ​​created_at 열의 연관성을 기준으로 정렬하는 방법은 무엇입니까?

내가 즐겨 찾기 협회의 created_at 컬럼에 의해 사용자의 마음에 드는 게시물을 정렬 할
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 

. 그러나이 속성은 Post created_at 속성에 의해 정렬되며 Favorites created_at 속성에는 정렬되지 않습니다. 어떻게 즐겨 찾기 created_at 속성으로 정렬 할 수 있습니까?

@[email protected]('created_at DESC') 
+0

당신은 질문을 바꿔 수 있습니까? – beck03076

답변

15

order by 절에서 사용할 테이블을 지정해야합니다.

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

해야합니다.

하나의 멋진 트릭은 연관을 검사 할 때 레일 콘솔을 사용하는 것입니다. 특히, 수행중인 활동 레코드 조회에 'to_sql'메소드를 사용하는 것이 도움이됩니다. 예를 들어

: 설정 기본 순서에 대한 귀하의 게시물 모델

% bundle exec rails console 

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

위대한 작품입니다. 필자의 경우 @posts = @ user.favorited.order ('favorites.created_at DESC') 때문에 즐겨 찾기 created_at 속성으로 정렬됩니다. 제안 해 주셔서 감사합니다. –

+0

제대로 작동하지 않는 것 같아서 더 많은 정보로 편집했습니다. –

3

사용이 :

default_scope { order("created_at DESC") } 
관련 문제