So I have this fairly basic migration bit of code
class AddCounterCache < ActiveRecord::Migration
def self.up
add_column ''products'',
''backlog_items_count'', :integer, :default =>
0
end
def self.down
remove_column ''products'',
''backlog_items_count''
end
end
What I want to do in that is automatically update the
backlog_items_count on the way through the script, so in my console I
tried the following
>> pro = Product.find_all => [#<Product:0x409a6c34
@attributes={"name"=>"Product 1",
"sprints_count"=>"0",
"creator_id"=>"0", "id"=>"1",
"backlog_items_count"=>"0",
"update_user_id"=>"0",
"owner"=>"0", "created"=>"2006-07-13
12:21:12", "updated"=>nil, "due"=>nil}>]
>> pro.each { |p| puts p.backlog_items.size } 0 =>
[#<Product:0x409a24b8 @attributes={"name"=>"Product
1", "sprints_count"=>"0",
"creator_id"=>"0", "id"=>"1",
"backlog_items_count"=>"0",
"update_user_id"=>"0",
"owner"=>"0", "created"=>"2006-07-13
12:21:12", "updated"=>nil, "due"=>nil},
@backlog_items=[]>]
Notice the 0 records for backlog_items there... However if I do....
>> p = Product.find(1) => #<Product:0x40995b28
@attributes={"name"=>"Product 1",
"sprints_count"=>"0",
"creator_id"=>"0", "id"=>"1",
"backlog_items_count"=>"0",
"update_user_id"=>"0",
"owner"=>"0", "created"=>"2006-07-13
12:21:12", "updated"=>nil, "due"=>nil}>
>> p.backlog_items => [#<BacklogItem:0x40993e54
@attributes={"name"=>"Item 1",
"creator_id"=>"0", "assets"=>nil,
"product_id"=>"1",
"priority"=>"1", "id"=>"1",
"update_user_id"=>"0",
"owner_id"=>"0", "created"=>"2006-07-13
12:40:33", "updated"=>nil}>]
Notice it found one and of couse now if I do p.backlog_items.size it
returns 1
So I added this bit of code to the migration
# Reset the column
Product.reset_column_information
say_with_time "Updating products..." do
Product.find(:all).each do |p|
blg = p.backlog_items
p.backlog_items_count = blg.size
end
end
But it still sets the count to 0 where it should be 1, any help
appreciated...
--
Posted via http://www.ruby-forum.com/.