【问题标题】:To Interface or Not?: Creating a polymorphic model relationship in Ruby on Rails dynamically是否接口?:在 Ruby on Rails 中动态创建多态模型关系
【发布时间】:2011-02-18 06:36:54
【问题描述】:

请稍等片刻,我将尝试准确解释我想要实现的目标。

在我的 Ruby on Rails 应用程序中,我有一个名为 Page 的模型。

它代表一个网页。

我想让用户能够任意将组件附加到页面。 “组件”的一些示例包括 Picture、PictureCollection、Video、VideoCollection、Background、Audio、Form、Comments。

目前我在页面和图片之间有这样的直接关系:

class Page < ActiveRecord::Base
  has_many :pictures, :as => :imageable, :dependent => :destroy
end

class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
end

这种关系使用户可以将任意数量的图片与页面相关联。现在,如果我想提供多个集合,我需要一个额外的模型:

class PictureCollection < ActiveRecord::Base
  belongs_to :collectionable, :polymorphic => true
  has_many :pictures, :as => :imageable, :dependent => :destroy
end

并更改页面以引用新模型:

class Page < ActiveRecord::Base
  has_many :picture_collections, :as => :collectionable, :dependent => :destroy
end

现在用户可以向页面添加任意数量的图像集合。

但是,就 Page 模型中的 :picture_collections 引用而言,这仍然是非常静态的。如果我添加另一个“组件”,例如:video_collections,我需要在页面中为该组件类型声明另一个引用。

所以我的问题是这样的:

我需要为每种组件类型添加新的引用,还是有其他方法?在 Actionscript/Java 中,我会声明一个接口 Component 并让所有组件都实现该接口,然后我可以只有一个属性 :components 包含所有动态关联的模型对象。

这就是 Rails,我确信有一个很好的方法可以实现这一点,但它对 Google 来说是一个棘手的问题。或许各位好心人有一些明智的建议。提前感谢您抽出宝贵时间阅读并回答此问题。

【问题讨论】:

    标签: ruby-on-rails activerecord polymorphism orm


    【解决方案1】:

    我相信你可以只使用

    class Page < ActiveRecord::Base
      has_many :components, :as => :attachable, :dependent => :destroy
    end
    
    class Picture < ActiveRecord::Base
      belongs_to :attachable, :polymorphic => true
    end
    
    class PictureCollection < ActiveRecord::Base
      belongs_to :attachable, :polymorphic => true
      has_many :pictures, :as => :imageable, :dependent => :destroy
    end
    

    等等……

    【讨论】:

    • 嗨,J,我试过这个,但是当我访问 Page.components 时,我一直收到 uninitialized constant Page::Component 错误 你有什么建议可以解决这个问题吗?谢谢
    • 我在想......也许你必须定义每个关系......或者定义一个Component类并使PicturePictureCollection从这个类派生。
    猜你喜欢
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 2011-01-24
    相关资源
    最近更新 更多