【发布时间】: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