Forum: Ruby on Rails Code works in Console but crashes 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.
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
  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"

end


class AddUserData < ActiveRecord::Migration
  def self.up

    role = Role.find_by_role('User')
    team1 = DimTeam.find_by_team_name('Essex')
    user = User.new
    user.login = "snapes"
    user.email = "removed_email_address@domain.invalid"
    user.password = "password"
    user.password_confirmation = "password"
    user.role = role
    user.save
    user = User.find_by_login("snapes")
    user.dim_teams << team1

  end

  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
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?

dwh
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...
Martin
This topic is locked and can not be replied to.