HABTM - what am I doing wrong?


#1

For some reason, Rails keeps using the subject_id for id field in the
items_subjects table. This causes a problem when I try to add a second
item with the same subject as a proceeding item. I expect
items_subjects to be using the auto_increment for its id field instead
of manually setting it to the subject_id…

Below is my code. I’m running Rails 0.14.3.

Thanks,
Charles

require ‘rubygems’
require_gem ‘activerecord’

class Item < ActiveRecord::Base
has_and_belongs_to_many :subjects
end

class Subject < ActiveRecord::Base
has_and_belongs_to_many :items
end

class Items_Subjects < ActiveRecord::Base

end

Item.establish_connection(
:adapter => ‘mysql’,
:host => ‘localhost’,
:username => ‘root’,
:password => ‘password’,
:database => ‘retainit_test’
)

Subject.establish_connection(
:adapter => ‘mysql’,
:host => ‘localhost’,
:username => ‘root’,
:password => ‘password’,
:database => ‘retainit_test’
)

Items_Subjects.establish_connection(
:adapter => ‘mysql’,
:host => ‘localhost’,
:username => ‘root’,
:password => ‘password’,
:database => ‘retainit_test’
)

Subject.delete_all
Item.delete_all
Items_Subjects.delete_all

Subject.create :name => “math”
Subject.create :name => “addition”
Subject.create :name => “subtraction”

@item = Item.new
@item.question = “1+1=”
@item.answer = “2”
@item.save

@subject = Subject.find(:first, :conditions => “name = ‘math’” )
@subject2 = Subject.find(:first, :conditions => “name = ‘addition’” )
@item.subjects.push( [@subject, @subject2] )

@item = Item.new
@item.question = “4-4=”
@item.answer = “0”
@item.save

@subject3 = Subject.find(:first, :conditions => “name = ‘math’” )
@item.subjects.push( [@subject3] )

DROP TABLE IF EXISTS retainit_test.items;
CREATE TABLE retainit_test.items (
id int(11) NOT NULL auto_increment,
question text,
answer text,
difficulty float default NULL,
stage varchar(255) default NULL,
iteration int(11) default NULL,
due datetime default NULL,
lastlearned datetime default NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS retainit_test.items_subjects;
CREATE TABLE retainit_test.items_subjects (
id int(11) NOT NULL auto_increment,
subject_id int(11) default NULL,
item_id int(11) default NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS retainit_test.subjects;
CREATE TABLE retainit_test.subjects (
id int(11) NOT NULL auto_increment,
name varchar(255) default NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;