I added a counter_cache to an existing parent-child model pair and 
wanted to set all the values for the counter_cache but can't do it 
using update_attribute (or a number of other methods).

Should I create a bug report?

I created a simple test app in 2.2.1 to isolate the problem.

# create the learner and learner_session models and migrations:

script/generate model learner name:string learner_session_id:integer
script/generate model learner_session learner_id:integer
rake db:migrate

# add the associations to the models:

class Learner < ActiveRecord::Base
   has_many :learner_sessions
end

class LearnerSession < ActiveRecord::Base
   belongs_to :learner
end

# create a learner and 2 learner sessions without a counter_cache

$ script/console

>>  l = Learner.create(:name => "stephen")
=> #<Learner id: 1, name: "stephen", learner_session_id: nil>

>>  l.learner_sessions.create
=> #<LearnerSession id: 1, learner_id: 1>

>>  l.learner_sessions.create
=> #<LearnerSession id: 2, learner_id: 1>

>>  l.learner_sessions.count
=> 2

# now run this migration:

class AddCounterCacheToLearners < ActiveRecord::Migration
   def self.up
     add_column :learners, :learner_sessions_count, :integer, :default => 0
     # Learner.reset_column_information
   end

   def self.down
     remove_column :learners, :learner_sessions_count
   end
end

# and add the counter_cache to the belongs_to association

class LearnerSession < ActiveRecord::Base
   belongs_to :learner, :counter_cache => true
end

# back into script/console

$ script/console

>>  l = Learner.find(:first)
=> #<Learner id: 1, name: "stephen", learner_session_id: nil, 
learner_sessions_count: 0>

# there are still 2 learner sessions:

>>  l.learner_sessions.count
=> 2

# but the learner_sessions_count is not set yet:

>>  l.learner_sessions_count
=> 0

# update the learner_sessions_count:

>>  l.update_attribute(:learner_sessions_count, 2)
=> true

# it is written to the model object:

>>  l
=> #<Learner id: 1, name: "stephen", learner_session_id: nil, 
learner_sessions_count: 2>

>>  l.learner_sessions_count
=> 2

# but not to the database

>>  l = Learner.find(:first)
=> #<Learner id: 1, name: "stephen", learner_session_id: nil, 
learner_sessions_count: 0>


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to