Should a Thread and a Post be the same model in a web app?
I'm creating a new forum web app in rails.
Should a Thread and a Post be the same model or a different model?
What are the advantages and disadvantages of each option ? when should i开发者_运维知识库t be the same model and when should i choose to separate the two ?
Thread - has a title and a body. has many posts.
Post - has only body, the posts are arranged as a tree (acts_as_tree)
Edit : they both can be voted on, only a thread can be tagged
The fact that Posts and Threads both have a body isn't enough to make them the same model. They are different enough to be different models, especially when you have a clear one-to-many relationship.
You probably want to read about associations, particularly has_many (which includes has_many :through), has_and_belongs_to_many, and belongs_to.
In this case, make Thread's has_many refer to Post. My guess is that a Post can only be in one thread. If so, then you want Post's belongs_to to refer to Thread.
I would presume you can go down both the Threads (1) to Posts (N) path AND the Posts-only model.
If the exact same data is being stored for both, I don't see why you CAN'T model it all as one table. Here's how:
CREATE TABLE posts
(
post_id serial,
post_thread_id int,
post_number int,
post_title character varying,
...
PRIMARY KEY(post_id)
);
INSERT INTO posts(post_thread_id, post_number, post_title) VALUES (1, 1, 'Welcome to my thread!');
INSERT INTO posts(post_thread_id, post_number, post_title) VALUES (1, 2, 'The first response!');
INSERT INTO posts(post_thread_id, post_number, post_title) VALUES (1, 3, 'The second response!');
Obviously, there's some undesirable bits and pieces to such a design, but...it can be done.
精彩评论