Reputation: 815
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:
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
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