I have the following (simple) scenario in a community project:
There is a simple messaging system where users can send messages to one
or many other users (comparable to email). So a message has one user as
sender and many users as recipients. I’ve modeled it like this:
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,
primary key(id)
) engine = InnoDB, character set utf8;
create table message_users (
id INT NOT NULL AUTO_INCREMENT,
message_id int not null,
user_id int not null,
primary key(id)
) engine = InnoDB, character set utf8;
and in Rails:
class Message < ActiveRecord::Base
belongs_to :user # sender
has_many :message_users
has_many :users, :through => :message_user #recipients
end
class MessageRecipient < ActiveRecord::Base
belongs_to :message
belongs_to :user
end
class User < ActiveRecord::Base
has_many :message_users
has_many :messages, :through => :message_users
end
What I don’t like here is that a message has message.user as sender and
message.users as recipients. I would like to be able to call something
like this:
message.sender
message.recipients
user.messages
message.recipients << u
Another problem might be that user.messages is not clearly defined in my
code as it could be all messages the user has sent or all messages that
a user has received.
How can I achieve a better solution? Maybe you can help me out…