This project is archived and is in readonly mode.
named_scope does not respect eager loading
-
elDub
- Tag set to eager_loading, named_scope
I have been battling with this issue as well. I think the problem is more related to 'has_one' relationships though.
class Document < ActiveRecord::Base has_one :revision, :class_name => 'Document', :foreign_key => 'prior_revision_id' belongs_to :prior_revision, :class_name => 'Document', :foreign_key => 'prior_revision_id' named_scope :active, :conditions => { :active => true } named_scope :inactive, :conditions => { :active => false } endAnd then in script/console:
Loading development environment (Rails 2.1.0) >> d1 = Document.create(:active => false, :title => 'd1', :body => 'text') => #<Document id: 1, prior_revision_id: nil, title: "d1", body: "text", active: false, created_at: "2008-07-17 14:18:36", updated_at: "2008-07-17 14:18:36"> >> d2 = d1.create_revision(:active => true, :title => 'd2', :body => 'new text') => #<Document id: 2, prior_revision_id: 1, title: "d2", body: "new text", active: true, created_at: "2008-07-17 14:19:14", updated_at: "2008-07-17 14:19:14"> >> doc = Document.find(1, :include => :revision) => #<Document id: 1, prior_revision_id: nil, title: "d1", body: "text", active: false, created_at: "2008-07-17 14:18:36", updated_at: "2008-07-17 14:18:36"> >> doc.revision => #<Document id: 2, prior_revision_id: 1, title: "d2", body: "new text", active: true, created_at: "2008-07-17 14:19:14", updated_at: "2008-07-17 14:19:14"> >> ns_doc = Document.inactive.find(:all, :include => :revision)[0] => #<Document id: 1, prior_revision_id: nil, title: "d1", body: "text", active: false, created_at: "2008-07-17 14:18:36", updated_at: "2008-07-17 14:18:36"> >> ns_doc.revision => nilNote how the attempt to use eager loading within a named scope request causes the same document (id: 1) to NOT be able to access it's revision.
-
elDub
Please forgive/ignore my prior post. After re-thinking it, it is a different issue which I will create a new post for.
-
Tarmo Tänav
- State changed from new to invalid
- Tag changed from eager_loading, named_scope to eager_loading, named_scope
Since conditions on named_scope's can be arbitrarily complex SQL snippets it is impossible to filter the association by the named scope in AR alone, making an exception for simple hash based conditions does not seem likely to happen.