# Problem with has\_and\_belongs\_to\_many

**URL:** <https://www.ruby-forum.com/t/problem-with-has-and-belongs-to-many/92854>\
**Category:** Rails\
**Created:** [April 25, 2007, 1:56am UTC](https://www.ruby-forum.com/t/problem-with-has-and-belongs-to-many/92854 "2007-04-25T01:56:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![madiba](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/58956e/32.png) [@madiba](https://www.ruby-forum.com/u/madiba)\
**Post date:** [April 25, 2007, 1:56am UTC](https://www.ruby-forum.com/t/problem-with-has-and-belongs-to-many/92854/1 "2007-04-25T01:56:19Z")

</div>

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/](http://uzytkownik.jogger.pl/)  
(GNU/)Linux User: #425935 (see [http://counter.li.org/](http://counter.li.org/))
