Hi all,
I am starting out learning Ruby on Rails (coming from a PHP background)
and I have a question about proper database design.
Let me give you a quick example of what I want to do:
Database:
CREATE TABLE users (
id int(11) NOT NULL auto_increment,
login varchar(40) default NULL,
email varchar(100) default NULL,
crypted_password varchar(40) default NULL,
salt varchar(40) default NULL,
created_at datetime default NULL,
updated_at datetime default NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE messages (
id int(11) NOT NULL auto_increment,
message text NOT NULL,
date datetime NOT NULL default ‘0000-00-00 00:00:00’,
sender_id int(11) NOT NULL default ‘0’,
receiver_id int(11) NOT NULL default ‘0’,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
(I’m using acts_as_authenticated for my user management.)
Whenever a message is sent, I want both the sender_id and the
receiver_id to point to the user_id. I guess I am wanting to know what
is the best way to go about setting up the model file when you have two
fields that point to the same table id.
I realize that I could separate the message table out to something like
this and use HABTM:
CREATE TABLE senders (
message_id int(11) NOT NULL default ‘0’,
sender_id int(11) NOT NULL default ‘0’,
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE receivers (
message_id int(11) NOT NULL default ‘0’,
receiver_id int(11) NOT NULL default ‘0’,
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE messages (
id int(11) NOT NULL auto_increment,
message text NOT NULL,
date datetime NOT NULL default ‘0000-00-00 00:00:00’,
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
but that just seems like a lot of bloat when the original design would
work great. It also does not excite me to have to create three tables
for what would usually only take one table, especially when the database
starts to expand to contain other tables that may have similar
circumstances.
Thanks in advance.