Migrating a Field to External Model

I have a model Product with an attribute ‘brand’. Currently it is a
simple attribute, however, I am migrating it to a separate model
Brand so that I can have other attributes with each brand. I created
the the model and created and ran the migration to create the new
table. So far so good. Then I created a separate migration to
transfer the data. The up method looks like this:

#Migrate Product Brands
add_column :products, :brand_id, :integer

Product::reset_column_information

Product::find(:all).each do |p|
brand = Brand::create(‘name’ => p.attributes[‘brand’]) unless
brand = Brand::find_by_name(p.attributes[‘brand’])
p.brand = brand
p.save!
end

remove_column :products, :brand

The problem is that p.save! is crashing with a cryptic error,
somewhere within validations. I have tried creating a brand,
associating it, and saving it like this in the console and it seems
to work fine. However ‘rake migrate’ consistently fails (both with
save! and with save). Here’s the relevant section of the stack trace:

wrong number of arguments (1 for 2)
/usr/local/lib/ruby/gems/1.8/gems/rake-0.7.1/lib/rake.rb:812:in link' /usr/local/lib/ruby/gems/1.8/gems/rake-0.7.1/lib/rake.rb:812:inlink’
/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/
active_record/validations.rb:300:in validates_each' /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/ active_record/validations.rb:299:invalidates_each’
/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/
active_record/validations.rb:794:in run_validations' /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/ active_record/validations.rb:788:inrun_validations’
/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/
active_record/validations.rb:752:in valid_without_callbacks' /usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/ active_record/callbacks.rb:306:invalid?’
/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/
active_record/validations.rb:733:in save!' ./db/migrate//012_decouple_categories_brands.rb:11:inreal_up’

Am I doing something wrong? Is this a Rails bug? I’m guessing
someone with deep knowledge of Rails internals will be able to
immediately see what’s going on. Since it’s happening in
validations maybe the model is helpful as well:

class Product < ActiveRecord::Base
belongs_to :brand

validates_presence_of :name

file_column :image, :magick => { :versions => { “thumb” =>
“50x50”, “medium” => “175x125>” } }
end

By the way, I’m new to the list, so please let me know if I should be
posting code snippets externally somewhere or other etiquette
issues. Thanks, Gabe

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