weird counter behaviour in has_many :through relationship

The counter is not working as I expected in has_many :through relationship.

I have very simple models. The Article and Pubtype models are in many-to-many relationship, which is stored in the ArticleType model.

Here are the models:

class Article < ActiveRecord::Base   has_many :article_types   has_many :pubtypes, :through => :article_types end

class Pubtype < ActiveRecord::Base   has_many :article_types   has_many :articles, :through => :article_types end

class ArticleType < ActiveRecord::Base   belongs_to :article   belongs_to :pubtype end

Here is the actual schema:

ActiveRecord::Schema.define(:version => 8) do ...   create_table "article_types", :force => true do |t|     t.column "article_id", :integer     t.column "pubtype_id", :integer   end

  create_table "articles", :force => true do |t|     t.column "title", :text   end

  create_table "pubtypes", :force => true do |t|     t.column "title", :string     t.column "articles_count", :integer, :default => 0, :null => false   end ... end

And here is the weird situation ('>>' is irb and '##' is log):

pubtype = Pubtype.find(1)

=> #<Pubtype:0x337a728 @attributes={"title"=>"News", "id"=>"1", "articles_count"=>"1"}>

## Pubtype Load (0.000559) SELECT * FROM pubtypes WHERE ( = 1)


=> 1

## Article Load (0.008023) SELECT articles.* FROM articles INNER JOIN article_types ON = article_types.article_id WHERE ((article_types.pubtype_id = 1))

Here, the already loaded "articles_count" attribute value of the pubtype object is not used and a actual select sql was called to count the number of articles that belong to the pubtype. It seems that rails intercepted the method call and did an unnecessary magic.

Is this an intentional behaviour for some good reason?

I'm running on the edge rails.

About your application's environment Ruby version 1.8.5 (i686-darwin8.8.1) RubyGems version 0.9.0 Rails version 1.2.0 Active Record version 1.14.4 Action Pack version 1.12.5 Action Web Service version 1.1.6 Action Mailer version 1.2.5 Active Support version 1.3.1 Edge Rails revision 5717 Application root /Users/joon/Sites/clickstream Environment development Database adapter mysql Database schema version 8

Hi. I dont now how it works in many_to_many models, but if it will be the model one_to_many, i can say, what you forgot the :counter_cahe => true parameter in Article model (if this parameter dont set, the field articles_count doesn't update automatically (in one_to_many models)). Sorry, if it is not your case.

Best Regards, Sergey