views:

494

answers:

1

Hello there,

I am having trouble getting this to work.

My problem is. I have A number of models (Article, Video, Photo)

Now I am trying to create a related_to association, such that

An article can have many other articles, videos and photos related to it. As can videos and photos.

Heres what I have tried

module 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

end

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

Then I have added acts_as_relatable to my three models (Article, Video, Photo) and included the module in ActiveRecord::Base

When trying in ./script/console I get it to add the related items and the ids work correctly however the source_type and related_type are always the same (the object that related_items was called from) I want the related_item to be the other model name.

Any ideas anyone?

A: 

I would use the has many polymorphs plugin since it supports double sided polymorphism you can do something like this:

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

and don't forget the db migration:

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

I don't know if "Relating" is a good name, but you get the idea. Now an article, video and photo can be related to another article, video or photo.

Jack Chu