2009-08-12 56 views
0

我有以下实体:用不同实体建模用户“友谊”的最佳方式是什么?

  • 用户
  • 公司
  • 组织

用户需要能够给用户,企业,组织,以及未来党的对象添加到自己的好友列表。

我最初的想法涉及使用友谊对象与多态关系的朋友,像这样:

简体友谊模式:

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

我的问题是Ruby on Rails的ActiveRecord不支持has_many通过关联连接表上的多态关系。

最后,我希望有一个单一的连接表可以遍历获得的所有类型的朋友,一定类型等列表如下图所示:

 
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) 

我认为使用户,业务和组织从一个通用的Party类继承,并将关联点指向基类Party类,但是在导致一堆垃圾字段的ORM环境中,它看起来很脏。

我想知道什么是别人怎么会接近这样的,你想通过使用ActiveRecord,同时避免这个错误常见的连接表来创建一个一对多的关系,类似对象的情况::)

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

任何建议非常感谢。

谢谢!

回答

0

看来,Rails插件“has_many_polymorphs”允许我做正是我想要的。

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

添加此行到我的用户模型给我我想要的功能:

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

不要使用:通过使用:如=> friendable相反在多态的has_many关系

+0

这里是链接,寻找多态关联 http://api.rubyonrails.org/ classes/ActiveRecord/Associations/ClassMethods.html – 2009-08-12 19:37:47

+0

我认为,但我需要朋友角色,这意味着我需要一个连接表。 – rwl4 2009-08-12 20:07:14

相关问题