HABTM migrations


#1

Bad rails day for Matt-

In a migration, for a habtm:

create_table :teams_users do |t|
  t.column :team_id,        :integer
  t.column :user_id,        :integer
end

Ok, fine. In a controller (well really a migration script):

@user.teams << Team.find( 3 )

And the SQL pumped at my server is:

INSERT INTO teams_users (team_id, id, user_id) VALUES (3, 3, 34)

Which promptly fails, because the id column already has a row with the
id of 3. I see one immediate solution:

  1. after create_table, remove_column :teams_users, ‘id’. If that’s even
    legal. Would be nice if create_table had it as an option to not make an
    ID column, but this’ll do.

But that seems sort of hackneyed. Is is a bug that the ID column is
being manually populated by rails? Doesn’t seem very senseble,
especially if the content of ID is always the same as team_id. Bug?
Feature?


Matthew B. :: removed_email_address@domain.invalid
Resume & Portfolio @ http://madhatted.com


#2

Matthew B. wrote:

Bad rails day for Matt-

But good day for answering my own questions.

  1. after create_table, remove_column :teams_users, ‘id’. If that’s even
    legal. Would be nice if create_table had it as an option to not make an
    ID column, but this’ll do.

That’s what this guy suggests: http://textsnippets.com/posts/show/340

And there is a key disable, it just wasn’t under the general migrations
documentation, it’s under the docs for the create_table method.

Still pretty ugly though.


Matthew B. :: removed_email_address@domain.invalid
Resume & Portfolio @ http://madhatted.com


#3

Check out http://wiki.rubyonrails.com/rails/pages/UsingMigrations

The Tables section tells you how to avoid adding an ID column in
automatically.

-Nick