It didn't exist before hand. ActiveRecord is triggering two inserts. I
have included a full example and the SQL

  catBike = Category.new(:name => "Bikes")
  catBike.save


  p = Product.new(:name => "Cannondale Bike", :price => 1000)
  p.save
  p.categories << catBike # This works great.

  p = Product.new(:name => "Trek Bike", :price => 900)
  p.categories << catBike # this causes two entriens to be created
  p.save


 Category Create (1.0ms)   INSERT INTO `categories` (`name`) VALUES
('Bikes')
 Product Create (0.0ms)   INSERT INTO `products` (`name`, `price`)
VALUES('Cannondale Bike', 1000)
 SQL (0.0ms)   COMMIT
 SQL (0.0ms)   BEGIN
 categories_products Columns (10.0ms)   SHOW FIELDS FROM
`categories_products`
 SQL (1.0ms)   INSERT INTO `categories_products` (`product_id`,
`category_id`) VALUES (1, 1)
 SQL (0.0ms)   COMMIT
 SQL (0.0ms)   BEGIN
 SQL (0.0ms)   COMMIT
 SQL (0.0ms)   BEGIN
 Product Create (1.0ms)   INSERT INTO `products` (`name`, `price`)
VALUES('Trek Bike', 900)
 categories_products Columns (7.0ms)   SHOW FIELDS FROM
`categories_products`
 SQL (1.0ms)   INSERT INTO `categories_products` (`product_id`,
`category_id`) VALUES (2, 1)
 categories_products Columns (7.0ms)   SHOW FIELDS FROM
`categories_products`
 SQL (0.0ms)   INSERT INTO `categories_products` (`product_id`,
`category_id`) VALUES (2, 1)
 SQL (0.0ms)   COMMIT

On Mar 16, 4:50 pm, Phlip <[email protected]> wrote:
> > p.categories now has TWO catBike
>
> Because << does not ask questions. It just adds a catBike. If you already had
> one, now you have two.
>
> You might need some combination of these:
>
>    a :unique => true on the habtm (spelling?)
>    a unique key (index) on the database
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to