【问题标题】:Rails 3 Polymorphic Associations, User model with multiple content items?Rails 3多态关联,具有多个内容项的用户模型?
【发布时间】:2012-06-13 01:38:41
【问题描述】:

在 Rails 3 中,我正在尝试对用户内容系统进行建模,用户可以在其中发布不同类型的内容,例如便笺、照片、网址等。

从 Java/C# OO 的角度来看,我会在用户和表示内容项的接口之间使用多态关系,例如叫IUserContent的东西。

我正在努力寻找一个符合我期望的示例,这是我首先尝试的,简而言之,我对 ActiveRecord 中多态关联的实现感到困惑。

# user.rb model - includes...

has_many :notes, :as => :postable, :dependent => :destroy, :inverse_of => :postable
has_many :urls, :as => :postable, :dependent => :destroy, :inverse_of => :postable
has_many :photos, :as => :postable, :dependent => :destroy, :inverse_of => :postable


# url.rb ... 

belongs_to :postable, :polymorphic => true, :inverse_of => :urls


# photo.rb

belongs_to :postable, :polymorphic => true, :inverse_of => :photos


# note.rb

belongs_to :postable, :polymorphic => true, :inverse_of => :notes

我仍然只是按照我找到的示例进行操作,坦率地说,这感觉用户是多态目标,而不是内容。

我想我想要这样的东西......

# within user.rb

has_many :postable, :as => :postable, dependent => :destroy, :inverse_of => :users

# photo.rb 
# url.rb
# note.rb
# all have the following...

belongs_to :user, :polymorphic => true, :inverse_of => :postable

...寻找一些正确方向的指针。

谢谢。

【问题讨论】:

    标签: ruby ruby-on-rails-3 activerecord polymorphic-associations


    【解决方案1】:

    您可以这样做的唯一方法是,如果所有这些类都继承自同一个基类,如下所示:

    class User < ActiveRecord::Base
      has_many :postable, :as => :postable, :dependent => :destroy, :class_name => 'Postable'
    end
    
    class Postable < ActiveRecord::Base
      belongs_to :user, :polymorphic => true
    end
    
    class Photo < Postable
    end
    
    class Url < Postable
    end
    
    class Note < Postable
    end
    

    因此,您必须使用 ActiveRecord 单表继承来建模这种关系。

    【讨论】:

    • 谢谢,我试一试,需要在任何地方引用课程内容吗?以has_many 为例。仅从命名的角度来看,我想调用超类 Postable 或 Content ,然后基于该类名进行关联,我会走吗?
    • 哎呀,我的错,你需要在 has_many :postable 定义中设置它,或者,而不是调用它 Content 调用它 可发布.
    • 哦,我需要在 DB 模式中处理什么?
    • 您需要为它们创建字段和适当的索引 - techbot.me/2008/09/…
    猜你喜欢
    • 2018-01-05
    • 2012-05-23
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多