0

I want to have a polymorphic relationship so that many videos, tags, and users can be posted to profiles. Profiles, videos, tags, and users are all separate resources. Would I need a separate model for this and combine some sort of has_many through association with polymorphism? I want profiles to have many videos, tags and users, but also videos, tags and users to have many profiles.

Justin Meltzer
  • 13,318
  • 32
  • 117
  • 182

3 Answers3

1

Why using polymorphism, when the has_and_belongs_to_many association seems to be the perfect match?

rausch
  • 3,148
  • 2
  • 18
  • 27
  • because then I would need three separate join tables? – Justin Meltzer Apr 23 '11 at 06:19
  • That's correct and IMHO the way to go here, as it is less complex and probably faster. Of course you can also go with polymorphism, then (if I understand you correctly) you will need one join table (`profilable_profile`) and a `profilable_type` column in your profiles table. Your Profile model would need a `has_and_belongs_to_many :profilables`, all others a `has_and_belongs_to_many :profiles`. – rausch Apr 23 '11 at 07:07
  • I'm slightly confused how polymorphism would work here. Could you perhaps provide the full example with the table fields so I can determine which one to do? – Justin Meltzer Apr 23 '11 at 15:44
0

I think this is help for you. http://railscasts.com/episodes/154-polymorphic-association

Mr. Black
  • 11,692
  • 13
  • 60
  • 85
0

You do not need polymorphic associations for this one. Instead you need has_many and has_many through associations.

Profiles have many videos and videos have many profiles is (in plain english) :

Profile has many videos through profile_videos
Video has many profiles through profile_videos

ProfileVideo belongs to profile
ProfileVideo belongs to video

Using that, you can now do either profile.videos to get a profile videos, or video.profiles to get a video's profiles.

Spyros
  • 46,820
  • 25
  • 86
  • 129
  • but what about with users? would that cause a conflict because a user already has_one profile? – Justin Meltzer Apr 24 '11 at 04:04
  • ok. Then I would need several join tables... so I decided to use the `has_many_polymorphs` plugin, but now I'm experiencing this problem: http://stackoverflow.com/questions/5768764/how-to-set-up-these-crud-controller-actions-for-has-many-polymorphs-and-an-error would you mind checking it out? I might just decide to go to your solution if I cant get this to work... – Justin Meltzer Apr 24 '11 at 07:05
  • also if I were to have three separate join tables like this, how would I get all three queries combined into one query that is ordered by `created_at`? – Justin Meltzer Apr 24 '11 at 18:03