icem
icem

Reputation: 747

ActiveRecord query with named scope returns wrong id for associated objects

Models code:

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

I've got something strange with querying with named_scope by associated object:

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

Why in second case I've got wrong ids? Any ideas? Generated sql query is good and it returns right ids (10, 11).

I'm using rails 2.3.11, mysql db, ruby ee.

Upvotes: 0

Views: 646

Answers (2)

Tilo
Tilo

Reputation: 33732

the result from ProductGroup.last.products.sort_by_priority are not database records that's why the IDs are not corresponding to database record IDs..

Do this instead:

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

If you're using Rails >= 3.0 this should also work:

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

Upvotes: 1

user979912
user979912

Reputation:

what does

ProductGroup.last.products.sort_by_priority.class

return? it is probably not an ActiveRecord::Relation object

Upvotes: 1

Related Questions