Forum: Ruby on Rails "Owning" a polymorphic

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B5ab0f0a6f14d4c2e8115dc315e41484?d=identicon&s=25 Eric Schultz (wwahammy)
on 2006-03-31 13:01
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?
D5145c421cd25af6fa577c15219add90?d=identicon&s=25 unknown (Guest)
on 2006-03-31 13:12
(Received via mailing list)
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
Db59927495b7db991b543d113e1835ff?d=identicon&s=25 Maurice Codik (Guest)
on 2006-03-31 17:18
(Received via mailing list)
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
This topic is locked and can not be replied to.