1

我有许多模型(文章、视频、照片)

现在我正在尝试创建一个related_to 关联,这样

一篇文章可以有许多与之相关的其他文章、视频和照片。视频和照片也可以。

这是我尝试过的:

模块 ActsAsRelatable

def self.included(base)
  base.extend(ClassMethods)
end

module ClassMethods
    def acts_as_relatable
        has_many :related_items, :as => :related
        has_many :source_items, :as => :source, :class_name => 'RelatedItem'
    end
end

结尾

类 RelatedItem < ActiveRecord::Base belongs_to :source, :polymorphic => true belongs_to :related, :polymorphic => true end

然后我在我的三个模型(文章、视频、照片)中添加了acts_as_relatable,并将该模块包含在 ActiveRecord::Base 中

在 ./script/console 中尝试时,我让它添加相关项目并且 id 可以正常工作,但是 source_type 和 related_type 始终相同(从中调用related_items 的对象)我希望related_item 是另一个模型名称。

有什么想法吗?

4

1 回答 1

0

我会使用has many polymorphs插件,因为它支持双面多态,你可以这样做:

class Relating < ActiveRecord::Base
    belongs_to :owner, :polymorphic => true
    belongs_to :relative, :polymorphic => true

    acts_as_double_polymorphic_join(
      :owners => [:articles, :videos, :photos],
      :relatives => [:articles, :videos, :photos]
    )
end

并且不要忘记数据库迁移:

class CreateRelatings < ActiveRecord::Migration
  def self.up
    create_table :relating do |t|
      t.references :owner, :polymorphic => true
      t.references :relative, :polymorphic => true
    end
  end

  def self.down
    drop_table :relatings
  end
end

我不知道“关系”是否是个好名字,但你明白了。现在一篇文章、视频和照片可以与另一篇文章、视频或照片相关联。

于 2009-03-01T07:53:22.637 回答