2011-10-08 72 views
0

型號代碼:ActiveRecord的查詢與命名範圍返回錯誤ID爲關聯對象

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :product_groups 
    belongs_to :accessible_fields_group 

    named_scope :sort_by_priority, :joins => :accessible_fields_group, :order => "priority ASC" 
end 

class ProductGroup < ActiveRecord::Base 
    has_and_belongs_to_many :products 
end 

我已經得到了一些奇怪的事情與相關聯的對象與named_scope查詢:

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

爲什麼在第二種情況下我有錯的ID嗎?有任何想法嗎?生成的sql查詢很好,它會返回正確的id(10,11)。

我使用rails 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)'返回產品的關聯對象id,因爲它被連接查詢所迷惑了?我不知道軌道2,所以不知道 –

回答

1

ProductGroup.last.products.sort_by_priority結果不是數據庫記錄 這就是爲什麼ID是不對應的數據庫記錄ID ..

做到這一點,而不是

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

如果您使用的Rails> = 3.0這也應該工作:

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

什麼呢

ProductGroup.last.products.sort_by_priority.class 

回報?它可能不是一個ActiveRecord :: Relation對象

+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