Forum: Ruby on Rails associations not saved in migration

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Peter A. (Guest)
on 2008-10-07 06:14
hi.  i've got a couple migrations where i've added foreign keys and
tried to update them via the migration but my items don't save.  i've
used save! in the hopes that an exception gets raised but no luck.  the
migrations run without errors but the data isn't in the db.  can anyone
point out what i might be doing wrong?  thanks!  code below.

class AddDeliIdToMenuItem < ActiveRecord::Migration
  def self.up
    add_column :menu_items, :deli_id, :integer

    # todo - the code below doesn't work, wtf?
    deli = Deli.find(:first)
    items = MenuItem.find(:all)
    for item in items do
      item.deli = deli
      item.save!
    end
  end

  def self.down
    remove_column :menu_items, :deli_id
  end
end

class CreateTestMenuItemTypes < ActiveRecord::Migration
  def self.up
    type = MenuItemType.create :name => 'Sandwiches'
    items = MenuItem.find_all_by_item_type "Sandwhich"
    for item in items do
      puts "item: #{item.name}, type id: #{type.id}"
      item.menu_item_type_id = type.id
      puts "item: #{item.name}, type id: #{item.menu_item_type_id}"
      item.save!
    end
    type = MenuItemType.create :name => 'Salads'
    items = MenuItem.find_all_by_item_type "Salad"
    for item in items do
      puts "item: #{item.name}, type id: #{type.id}"
      item.menu_item_type_id = type.id
      puts "item: #{item.name}, type id: #{item.menu_item_type_id}"
      item.save!
    end
    type = MenuItemType.create :name => 'Drinks'
    type = MenuItemType.create :name => 'Smoothies'
    type = MenuItemType.create :name => 'Deserts'
    type = MenuItemType.create :name => 'Wraps'
  end

  def self.down
  end
end
This topic is locked and can not be replied to.