Migration not updating fields

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…

On 7/14/06, Chris L. [email protected] wrote:

appreciated…
Looks like you’re loaded the records, changing the items_count but
never actually saving them…

Tom

Tom W. wrote:

appreciated…
Looks like you’re loaded the records, changing the items_count but
never actually saving them…

Ive tried

Reset the column

Product.reset_column_information
say_with_time “Updating products…” do
Product.find(:all).each do |p|
bklg = p.backlog_items
p.update_attribute( ‘backlog_items_count’, bklg.size )
end
end

Still to no avail, but thanks anyway :slight_smile:

Chris L. wrote:

Okay I fixed it… well someone else did on another forum…

for future reference this is how…

Product.find(:all).each do |p|
p.update_attribute( ‘backlog_items_count’, p.backlog_items(true).size
)
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs