views:

217

answers:

2

I have the following entities:

  • User
  • Company
  • Organization

Users need to be able to add Users, Companies, Organizations, and future party objects to their friend list.

My original idea involved using a Friendship object with a polymorphic relationship to the friend like so:

Simplified Friendship schema:

  • user_id
  • friendable_id
  • friendable_type
User
- has_many :businesses, :through => :friendships, :conditions => ['friendable_type=?', 'Business'], :source => :friendable

My problem is that Ruby on Rails ActiveRecord does not support has_many through relationships through polymorphic relationships on the join table such.

In the end I want to have a single join table to be able to iterate through to get a list of friends of all types, certain types, etc. like below:

john = User.find(5)
john.friendships.map {|friendship| friendship.friendable }
john.businesses (has_many :through scoped to only the businesses)
john.organizations (has_many :through scoped only to the organizations)

I've considered making the User, Business, and Organization inherit from a generic Party class and making the association point to the base Party class, but in the context of an ORM that leads to a bunch of junk fields and it just seems dirty.

What I'd like to know is how others would approach a situation like this where you want to create one-to-many relationships to similar objects through a common join table using ActiveRecord while avoiding this error: :)

Cannot have a has_many :through association 'User#businesses' on the polymorphic object 'Friendship#friendable'.

Any advice greatly appreciated.

Thanks!

A: 

Do not use :through, use :as=>friendable instead in polymorphic has_many relationship

ez
here are the links, looking for polymorphic associationshttp://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
ez
I considered that, but I need friend roles, which means I need a join table.
rwl4
A: 

It appears that the Rails plugin 'has_many_polymorphs' allows me to do exactly what I want.

http://github.com/fauna/has_many_polymorphs/tree/master

Adding this line to my User model gave me the functionality I wanted:

has_many_polymorphs :friendables, :from => [:businesses, :organizations], :through => :friendships
rwl4