# Bug in habtm?

**URL:** <https://www.ruby-forum.com/t/bug-in-habtm/88165>\
**Category:** Rails\
**Created:** [March 8, 2007, 4:44pm UTC](https://www.ruby-forum.com/t/bug-in-habtm/88165 "2007-03-08T16:44:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![starburger](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/848f3c/32.png) [@starburger](https://www.ruby-forum.com/u/starburger)\
**Post date:** [March 8, 2007, 4:44pm UTC](https://www.ruby-forum.com/t/bug-in-habtm/88165/1 "2007-03-08T16:44:32Z")

</div>

To implement a simple messaging system for a community platform I’ve  
done the following code:

class Message \< ActiveRecord::Base  
belongs\_to :sender, :class\_name =\> ‘User’  
has\_and\_belongs\_to\_many :recipients, :class\_name =\> ‘User’  
end

class User \< ActiveRecord::Base  
has\_many :sent\_messages, :class\_name =\> ‘Message’  
has\_and\_belongs\_to\_many :received\_messages, :class\_name =\> ‘Message’  
end

with

CREATE TABLE users (  
id INT NOT NULL AUTO\_INCREMENT,  
login VARCHAR(80) NOT NULL,  
…  
primary key (id),  
INDEX (id)  
) engine = InnoDB;

create table messages (  
id INT NOT NULL AUTO\_INCREMENT,  
user\_id int not null,  
subject varchar(255),  
body text,  
created\_at DATETIME default NULL,  
modified\_at DATETIME default NULL,

```
primary key(id)

```

) engine = InnoDB, character set utf8;

create table messages\_users (  
message\_id int not null,  
user\_id int not null,

```
primary key(message_id, user_id)

```

) engine = InnoDB, character set utf8;

First everything seemed fine. But user.received\_messages delivers  
message objects that are DEFINITELY NOT in the database (wrong sender  
ID)!! I had only one singel message in the DB, but

user.received\_messages.first

yields a slightly other object than

Message.find :first

Strange, strange!!! A bug maybe?

---

<div class="post-metadata">

**Author:** ![starburger](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/848f3c/32.png) [@starburger](https://www.ruby-forum.com/u/starburger)\
**Post date:** [March 9, 2007, 6:28am UTC](https://www.ruby-forum.com/t/bug-in-habtm/88165/2 "2007-03-09T06:28:04Z")

</div>

No, its not a bug, the sql generated by the :first option returns  
whatever results matches it can be any record. It is the SQL that  
behaves this way, it is not Rails fault.
