2009-02-27 26 views
1

私はモデル(記事、ビデオ、写真)今ポリモーフィックhas_manyの自己参照

私は、

記事は、他の多くの記事を持つことができるように、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 ::ベース belongs_toの:ソース:多型=>真 belongs_toの:関連を:多形=> true end

次に、私の3つのモデル(記事、ビデオ、写真)にacts_as_relatableを追加し、ActiveRecord :: Baseにモジュールを含めました。

./script/consoleを試してみると、しかし、source_typeとrelated_typeは常に同じです(related_itemsが呼び出されたオブジェクト)。related_itemを他のモデル名にします。

+0

related_itemsで何をしようとしているのですか?コードの上で説明しましたが、source_itemsは何ですか? –

+0

コードブロックにすべてのコードが含まれるようにインデントを修正できるとすばらしいことでしょう。 – Benson

答えて

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 

私にはありませんの"Relating"が良い名前であるかどうかを知っているが、あなたはそのアイデアを得る。記事、ビデオ、写真は、別の記事、ビデオ、写真と関連付けることができます。