Forum: Ruby on Rails habtm questions

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.
Af656cca6a3806277fe19a0c606ddab7?d=identicon&s=25 Zac Elston (zaq)
on 2006-03-09 19:07
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:    		<td><%= package.bag.name%> </td>


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
C31c7255fa4488dfc5d766403b497a36?d=identicon&s=25 Jim Morris (Guest)
on 2006-03-11 00:01
(Received via mailing list)
There should not be an id column on the bags_packages table.
This topic is locked and can not be replied to.