I'm playing around with RoR and I'm having trouble figuring out how to describe a certain relationship. I'm building a social networking site where you have users who can comment on other users, photos, videos, and blogs. I've figured out how to have a comment belong to a user or media item through a polymorphic relationships but I dont' know how to have the comment also be "owned" by the user who made the comment. I've included some code to help with the description: #User class class User < ActiveRecord::Base has_many :photos has_many :blogs ... end #photo (also blog and video are similar) class Photo < ActiveRecord::Base belongs_to :user has_many :comments, :as => :commentable end #comment class class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true end #comment table includes the following fields: id content <--- the actual comment text user_id <--- the user who made the comment commentable_id commentable_type I've thought this over for 2 days and I still can't seem to figure out a way to describe what I want to describe... Does anyone have any ideas or suggestions on how to do this?
on 2006-03-31 13:01
on 2006-03-31 13:12
Maybe if you have an intermediate table, which links one-to-one to the users (maybe called "commentor"), then each comment can link to that? It's a little clunky, but less so than any alternative I can think so. That's the problem with rails' strict naming conventions... if you want to create more than one link between the same two tables, you're a bit stuck. Hope this helps. -Nathan
on 2006-03-31 17:18
I havent played with polymorphic associations yet, but is there some reason this wont work? class Comment <ActiveRecord::Base belongs_to :commentable, :polymorphic => true belongs_to :user end >That's the problem with rails' strict naming conventions... if you >want to create more than one link between the same two tables, you're >a bit stuck. Hope this helps. That's a common misconception. The naming is just a convention (or, an easy default)-- it can always be configured differently. class Comment <ActiveRecord::Base belongs_to :commentable, :polymorphic => true belongs_to :author, :class_name => "User", :foreign_key => "user_id" end Would work the same as the above. Maurice