Rails ActiveRecord :counter_cache not updated if assocation not set up before create. Intentional? -
i've implemented belongs_to relation :counter_cache => true , notice counter cache not updated if relation not set before initial save.
for instance, company has_many employees. if do
company.employees << employee.new(:name => "joe")
the counter gets updated correctly if do
company.employees << employee.create(:name => "joe")
the counter remains unchanged.
for more details, here models:
class employee < activerecord::base belongs_to :company, :counter_cache => true end class company < activerecord::base has_many :employees end
and here's rails console session demonstrates this:
loading development environment (rails 3.0.5) ruby-1.9.2-p180 :001 > company_a = company.create(:name => "acme") => #<company id: 1, name: "acme", created_at: "2011-07-22 01:31:39", updated_at: "2011-07-22 01:31:39", employees_count: 0> ruby-1.9.2-p180 :002 > company_a.employees << employee.new(:name => "bob") => [#<employee id: 1, company_id: 1, name: "bob", created_at: "2011-07-22 01:31:59", updated_at: "2011-07-22 01:31:59">] ruby-1.9.2-p180 :003 > company_a.reload => #<company id: 1, name: "acme", created_at: "2011-07-22 01:31:39", updated_at: "2011-07-22 01:31:39", employees_count: 1> ruby-1.9.2-p180 :004 > company_a.employees << employee.create(:name => "joe") => [#<employee id: 1, company_id: 1, name: "bob", created_at: "2011-07-22 01:31:59", updated_at: "2011-07-22 01:31:59">, #<employee id: 2, company_id: 1, name: "joe", created_at: "2011-07-22 01:32:28", updated_at: "2011-07-22 01:32:28">] ruby-1.9.2-p180 :005 > company_a.reload => #<company id: 1, name: "acme", created_at: "2011-07-22 01:31:39", updated_at: "2011-07-22 01:31:39", employees_count: 1>
the documentation counter incremented/decremented when object created/destroyed thinking should monitor updates useful. otherwise, say, moving employees between companies result in counters totally off.
is expected behavior? if so, what's rationale? , if not, doing wrong? tried in rails 3.0.5 , ruby 1.9.2
thanks!
Comments
Post a Comment