Forum: Ruby on Rails Problem with has_and_belongs_to_many

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.
1e8f141e7857d397d8020ed3b759e88a?d=identicon&s=25 Maciej Piechotka (Guest)
on 2007-04-25 01:56
(Received via mailing list)
Hello I have two models:
app/model/user.rb
class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
end
app/model/role.rb
class Role < ActiveRecord::Base
  has_and_belongs_to_many :users
end
And one controller:
class Admin::UsersController < ApplicationController
  # ...
  def user_save usr, id = nil
    roles = []
    usr[:roles].each_key do |role|
      roles << Role.find(:first, :conditions => {:id => role})
    end
    if id.nil?
      user = User.new :first_name => usr[:first_name],
                      :last_name => usr[:last_name]
    else
      user = User.find :first, :conditions => {:id => id}
      user.first_name = usr[:first_name]
      user.last_name = usr[:last_name]
    end
    user.save
    user.roles = roles
    user.save
  end

  private :user_save
end

% sqlite db/library_development.db
SQLite version 2.8.16
Enter ".help" for instructions
sqlite> SELECT * FROM roles_users;
1|1|1
sqlite> .schema roles_users
CREATE TABLE roles_users ("id" INTEGER PRIMARY KEY NOT NULL, "role_id"
integer DEFAULT NULL, "user_id" integer DEFAULT NULL, FOREIGN KEY
(role_id) REFERENCES roles (id), FOREIGN KEY (user_id) REFERENCES users
(id));
sqlite> .quit

From log:
  Role Load (0.000510)   SELECT * FROM roles WHERE (roles."id" = '1')
LIMIT 1
  User Load (0.000711)   SELECT * FROM users WHERE (users."id" = '2')
LIMIT 1
  SQL (0.000675)   PRAGMA table_info(users)
  User Indexes (0.000181)   PRAGMA index_list(users)
  User Update (0.058220)   UPDATE users SET "last_name" = 'xxxx',
"first_n
ame" = 'yyyy' WHERE "id" = 2
  SQL (0.000738)   PRAGMA table_info(roles_users)
  Role Load (0.000789)   SELECT * FROM roles INNER JOIN roles_users ON
roles.id
= roles_users.role_id WHERE (roles_users.user_id = 2 )
  SQL (0.000580)   PRAGMA table_info(roles)
  Role Indexes (0.000221)   PRAGMA index_list(roles)
  SQL (0.000629)   PRAGMA table_info(roles_users)
  SQL (0.000000)   SQLite::Exceptions::SQLException: PRIMARY KEY must be
unique:
 INSERT INTO roles_users ("role_id", "id", "user_id") VALUES (1, 1, 2)

What can be wrong? Why it inserts it owns id?
--
I've probably left my head... somewhere. Please wait untill I find it.
Homepage (pl_PL): http://uzytkownik.jogger.pl/
(GNU/)Linux User: #425935 (see http://counter.li.org/)
This topic is locked and can not be replied to.