具有命名范围的ActiveRecord查询返回关联对象的错误ID

时间:2011-10-08 17:54:15

标签: ruby-on-rails ruby activerecord

模型代码:

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。

2 个答案:

答案 0 :(得分:1)

是什么

ProductGroup.last.products.sort_by_priority.class

返回?它可能不是ActiveRecord :: Relation对象

答案 1 :(得分:1)

ProductGroup.last.products.sort_by_priority的结果不是数据库记录 这就是ID与数据库记录ID不对应的原因..

改为

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

如果您使用Rails&gt; = 3.0 ,这也应该有效:

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