Code works in Console but crashes in migration

I am using a habtm relationship between two tables and the migration fails when updating the join table. However, it works when doing it step by step in the console!

Here is the code: class User < ActiveRecord::Base   acts_as_authentic   belongs_to :role   has_and_belongs_to_many :dim_teams, :association_foreign_key => :team_id end

class DimTeam < ActiveRecord::Base

  set_primary_key "team_id"

  has_and_belongs_to_many :users, :foreign_key => "team_id"


class AddUserData < ActiveRecord::Migration   def self.up

    role = Role.find_by_role('User')     team1 = DimTeam.find_by_team_name('Essex')     user =     user.login = "snapes" = ""     user.password = "password"     user.password_confirmation = "password"     user.role = role     user = User.find_by_login("snapes")     user.dim_teams << team1


  def self.down   end end

When I run the code step by step in the console, it works. The final user.dim_teams << team1 line produces the following output in development.log: SQL (2.8ms) INSERT INTO [dim_teams_users] ([team_id], [user_id]) VALUES (13, 2)

When I run it as a rake task, I get SQL (0.0ms)[0m [0mDBI::DatabaseError: (102) [unixODBC][FreeTDS][SQL Server]Incorrect syntax near ')'.: INSERT INTO [dim_teams_users] () VALUES ()[0m

Can anybody explain why the difference to me please? thanks

Maybe team1 is nil when it’s being run in the migration? I would check it in debugger or add some logging statements just before that.

Any chance the migrations are being run against a different environment, and thus a different database?


Martin Hawkins wrote:

Useful idea about using logging statements. It's definitely the correct environment though... Martin