Tim Koelkebeck
Tim Koelkebeck

Reputation: 815

Hacker News rails clone: advice on modeling relationship between links, comments and votes

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:

I just added the Comment Model and thinking through how to integrate it with votes. Some options:

  1. Collapse links and comments into a single "Item" model, and map votes to the generic item_id
  2. Have two vote tables, one for comments, one for links
  3. 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!

Upvotes: 1

Views: 601

Answers (1)

Fernando Diaz Garrido
Fernando Diaz Garrido

Reputation: 3995

I think what you are looking for is a polymorphic association. In your case would be as simple as :

class Vote < ActiveRecord::Base
  belongs_to :votable, :polymorphic => true
end

class Link < ActiveRecord::Base
  has_many :votes, :as => :votable
end

class Comment < ActiveRecord::Base
  has_many :votes, :as => :votable
  #...
end

Your votes table should look like:

id           : integer
votable_id   : integer 
votable_type : string # Comment || Link

Here you have a Railscast about it: Polymorphic Associations Railscast

Upvotes: 3

Related Questions