Bug in habtm?


#1

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?


#2

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.