rails/rails — Issue #3271: [Rails 3.1.x] - Nested Has Many Through Conditions being Cached in Unrelated Queries
Author: camwest
Created: 2011-10-09 18:22:51+00:00
State: open

Schema & models & seeds:

```
# Schema
create_table "categories", :force => true do |t|
t.integer "approved_count"
end

create_table "categorizations", :force => true do |t|
t.integer "category_id"
t.integer "categorizable_id"
t.string "categorizable_type"
end

create_table "certifications", :force => true do |t|
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "courses", :force => true do |t|
t.integer "certification_id"
end

#Models

class Categorization < ActiveRecord::Base
belongs_to :categorizable, :polymorphic => true
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :categorizations
end
class Certification < ActiveRecord::Base
has_many :courses
has_many :categories,
:through => :courses,
:conditions => ["approved_count > 0"]
end
class Course < ActiveRecord::Base
belongs_to :certification
has_many :categorizations, :as => :categorizable
has_many :categories,
:through => :categorizations
end

# SEEDS:
cert = Certification.create
cert.categories.length #this causes the 'approved_count' condition to be cached

course = Course.create
category = course.categories.create(:approved_count => 0)

course.categories.to_sql #this includes the 'approved_count' condition even though it shouldn't
assert_equal category, course.categories.first
```

There is a workaround to getting this working and that is specifying the EXACT path through the associations. Namely:

```
class Certification < ActiveRecord::Base
has_many :courses
has_many :categorizations,
:through => :courses
has_many :categories,
:through => :categorizations,
:conditions => ["approved_count > 0"]
end
```

I'm not exactly sure if this is intended behaviour. Either way there should be an error if you're using an invalid nest...

How can I help to get this fixed?