2011-10-08 6 views
0

모델 코드에 대한 잘못된 ID를 반환액티브 쿼리 관련 개체

>> ProductGroup.last.products.map(&:id) 
=> [11, 10] 
>> ProductGroup.last.products.sort_by_priority.map(&:id) 
=> [1, 2] #<= WHY? 

왜 두 번째 경우에 I 잘못된 ID가있어? 어떤 아이디어? 생성 된 SQL 쿼리가 좋으며 오른쪽 ids (10,11)를 반환합니다.

레일즈 2.3.11, mysql db, ruby ​​ee를 사용하고 있습니다.

+0

'ProductGroup.last.products.sort_by_priority'는 무엇을 반환합니까? –

+0

ProductGroup.find (the_id_you_want_to_check) .products ... – tokland

+0

을 시도해보십시오. '조인'이 의심됩니다. 어쩌면'map (& : id)'는 조인 질의에 속아서 제품의 연관된 객체 ids를 반환 할까? 나는 잘 모르겠다. 레일 2를 모르겠다. –

답변

1

없는 대신 :

ProductGroup.last.products.sort_by_priority.all.map(&:id) 

당신이 레일> = 3.0이 또한 작동합니다 사용하는 경우 :

ProductGroup.last.products.order(:by => :priority).map(&:id) 
1

ProductGroup.last.products.sort_by_priority.class 

수익을 무엇? 그것은 ProductGroup.last.products.sort_by_priority의 결과가 IDS는이 데이터베이스 레코드 ID에 해당되지 않는 이유 ..

는이 작업을 수행 데이터베이스 레코드 아니다 아마 액티브 :: 관계 객체

+0

'?> ProductGroup.last.products.class' '=> Array' – icem

+0

'>> ProductGroup.last.products .sort_by_priority.class' '=> ActiveRecord :: NamedScope :: Scope' – icem

+0

질문에 답하는 @icem! 두 번째 호출에서 볼 수있는 ID는 ID ActiveRecord "레코드"가 아니지만 범위의 ID – Tilo