Forum: Ruby on Rails Code works in Console but crashes in migration

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Martin H. (Guest)
on 2009-01-23 18:45
(Received via mailing list)
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
  belongs_to :role
  has_and_belongs_to_many :dim_teams, :association_foreign_key
=> :team_id

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" = "removed_email_address@domain.invalid"
    user.password = "password"
    user.password_confirmation = "password"
    user.role = role
    user = User.find_by_login("snapes")
    user.dim_teams << team1


  def self.down

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
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?
Denis H. (Guest)
on 2009-01-24 18:18
(Received via mailing list)
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 H. (Guest)
on 2009-01-26 11:28
(Received via mailing list)
Useful idea about using logging statements. It's definitely the
correct environment though...
This topic is locked and can not be replied to.