Friday, October 30, 2009

has many polymorphic - double sided

I have used the following model relation to get the has many polymorphic double sided relation.

class Album < ActiveRecord::Base
has_many :album_files, :dependent => :destroy, :foreign_key => "album_id", :class_name => "AlbumFile"
has_many :photos, :source => :file, :through => :album_files, :source_type => "Photo", :class_name => "Photo"
has_many :videos, :source => :file, :through => :album_files, :source_type => "Viedo", :class_name => "Video"
end
class AlbumFile < ActiveRecord::Base
belongs_to :file, :polymorphic => true
end
class Photo < ActiveRecord::Base
has_many :album_files, :dependent => :destroy, :as => :file
has_many :albums, :source => :album, :foreign_key => "album_id", :through => :album_files, :class_name => "Album"
end
class Video < ActiveRecord::Base
has_many :album_files, :dependent => :destroy, :as => :file
has_many :albums, :source => :album, :foreign_key => "album_id", :through => :album_files, :class_name => "Album"
end


thats it..

Now we have associated Album with photos, videos through the mapping table album_files.

Following works for this

album = Album.create()
album.photos << Photo.create()
album.vidoes << Video.create()

album.album_files.count - returns the total count i.e, 2

album.photos - returns the count 1
album.vidoes - returns the count 1