Forum: Ruby on Rails Rails 1.2.2 HABTM error?

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.
13e4ba7f654dbbdd186d702c06c8b24c?d=identicon&s=25 Morten (Guest)
on 2007-02-12 17:16
(Received via mailing list)
Hi. I have the following models:

class User < ActiveRecord::Base
  has_and_belongs_to_many :rooms
end

class Room < ActiveRecord::Base
  has_and_belongs_to_many :users
end

And the test:

require File.dirname(__FILE__) + '/../test_helper'

class RoomTest < Test::Unit::TestCase

  def test_habtm
    u1 = User.create
    u2 = User.create

    r1 = Room.create
    r2 = Room.create

    r1.users << u1
    r1.users << u2
    r2.users << u2
  end
end

Running "rake test" results in the failure:

  1) Error:
test_habtm(RoomTest):
ActiveRecord::StatementInvalid: Mysql::Error: Duplicate entry '2' for
key 1: INSERT INTO rooms_users (`id`, `user_id`, `room_id`) VALUES (2,
2, 2)

The problem is, that Rails for some reason sets the "id" of the
rooms_users record to 2, rather than letting MySQL autoincrement
handle it.

Is this an error or am I missing something? Thanks.

Morten
9d1310212bb9dfe69ee6b259c7945392?d=identicon&s=25 Sheldon Hearn (sheldonh)
on 2007-02-12 19:00
(Received via mailing list)
On Feb 12, 6:15 pm, "Morten" <use...@kikobu.com> wrote:
>   1) Error:
> test_habtm(RoomTest):
> ActiveRecord::StatementInvalid: Mysql::Error: Duplicate entry '2' for
> key 1: INSERT INTO rooms_users (`id`, `user_id`, `room_id`) VALUES (2,
> 2, 2)
>
> The problem is, that Rails for some reason sets the "id" of the
> rooms_users record to 2, rather than letting MySQL autoincrement
> handle it.

Remove the id column from your join table and all will be well.  Rails
doesn't like surrogate keys on join tables, unless you model the join.

Ciao,
Sheldon.
This topic is locked and can not be replied to.