型號代碼: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。
ProductGroup.last.products.sort_by_priority返回什麼? –
嘗試ProductGroup.find(the_id_you_want_to_check).products ... – tokland
我懷疑'加入'。也許'map(&:id)'返回產品的關聯對象id,因爲它被連接查詢所迷惑了?我不知道軌道2,所以不知道 –