【问题标题】:Best way to model a user's "friendship" with different entities?模拟用户与不同实体的“友谊”的最佳方式?
【发布时间】:2010-11-19 01:57:00
【问题描述】:

我有以下实体:

  • 用户
  • 公司
  • 组织结构

用户需要能够将用户、公司、组织和未来的聚会对象添加到他们的朋友列表中。

我最初的想法是使用与朋友具有多态关系的 Friendship 对象,如下所示:

简化的友谊模式:

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

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

最后,我希望有一个单一的连接表,以便能够遍历以获取所有类型、某些类型等的朋友列表,如下所示:

约翰 = User.find(5) john.friendships.map {|友谊|友谊.Friendable } john.businesses (has_many :through 范围仅限于企业) john.organizations (has_many :through 仅适用于组织)

我考虑过让 User、Business 和 Organization 继承自一个通用的 Party 类并将关联指向基 Party 类,但在 ORM 的上下文中会导致一堆垃圾字段,而且它只是看起来很脏。

我想知道的是其他人将如何处理这种情况,您希望通过使用 ActiveRecord 的公共连接表创建与相似对象的一对多关系,同时避免此错误::)

不能有一个has_many:通过多态对象'Friendship#friendable'上的关联'User#businesses'。

非常感谢任何建议。

谢谢!

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations


    【解决方案1】:

    在多态 has_many 关系中不要使用 :through,而是使用 :as=>friendable

    【讨论】:

    【解决方案2】:

    Rails 插件“has_many_polymorphs”似乎允许我做我想做的事。

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

    将这一行添加到我的用户模型中给了我想要的功能:

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

    【讨论】:

      猜你喜欢
      • 2013-10-20
      • 2011-05-12
      • 2012-01-27
      • 1970-01-01
      • 2011-08-10
      • 2011-10-21
      • 2018-04-15
      • 2012-07-06
      • 1970-01-01
      相关资源
      最近更新 更多