Habtm questions


#1

I’ve got some of this working but other parts are ellusive.

I have

CREATE TABLE bags (
id int(11) NOT NULL auto_increment,
name varchar(255) NOT NULL default ‘’,
PRIMARY KEY (id)

CREATE TABLE packages (
id int(255) NOT NULL auto_increment,
name varchar(255) NOT NULL default ‘’,
PRIMARY KEY (id)

CREATE TABLE bags_packages (
id int(11) NOT NULL auto_increment,
bag_id int(11) NOT NULL default ‘0’,
package_id int(11) NOT NULL default ‘0’,
PRIMARY KEY (id)

class Package < ActiveRecord::Base
has_and_belongs_to_many :bags
end

do I need this below? the HABTM tutorial doesn’t say I do.
class Bag < ActiveRecord::Base
has_many :packages
end

problem A:
I can edit a package and select bags (using HABTM checkboxes) and
bags_packages is updated with
bag_id X package_id Y, but how do I get “package.bag.name” to display?

Showing app/views/packages/list.rhtml where line #15 raised:
undefined method `bag’ for #Package:0xb7adc610
15:

<%= package.bag.name%>

problem B:
save package “A” with bag “X” associated saves
save package “B” with bag “X” associated generates error

ActiveRecord::StatementInvalid in Packages#update
Mysql::Error: #23000Duplicate entry ‘1’ for key 1: INSERT INTO
bags_packages (id, bag_id, package_id) VALUES (1, 1, 38)

clearly the value of “1” for id is bad because it should be a newly
generated ID number. any idea where this is comming from?

thanks
-zaq


#2

There should not be an id column on the bags_packages table.