I’m loving Rails but we just started dating.
A user can vote on both links and comments. In addition to primary key and timestamp, I currently have the following attributes defined for these models:
- Link url, headline, submitter_id, score
- Comment content, commenter_id, score, link_id, parent_comment_id
- Vote id, voter_id, link_id, direction
I just added the Comment Model and thinking through how to integrate it with votes. Some options:
- Collapse links and comments into a single “Item” model, and map votes to the generic item_id
- Have two vote tables, one for comments, one for links
- Add comment_id column to existing Vote table
Not sure what’s best. #1 and #3 introduce dual-purpose tables, i.e. there are certain columns in a table that are only relevant to subsets of rows within that table. #2 avoids this problem, but seems redundant and silly.
Is the tradeoff inevitable or am I not seeing the golden path? What would you recommend? And if you happen to know of a rails repository on github that handles a similar situation, I’d really appreciate a link!
I think what you are looking for is a polymorphic association. In your case would be as simple as :
Your votes table should look like:
Here you have a Railscast about it: Polymorphic Associations Railscast