How to implement favorites in Rails with polymorphic associations

Ruby posted 8 months ago by christian

The code:

   1  class User < ActiveRecord::Base
   2    has_many :favorites
   3    has_many :favorite_feeds, :through =>  :favorites, :source => :favorable, :source_type => "Feed"
   4    has_many :favorite_entries, :through =>  :favorites, :source => :favorable, :source_type => "Entry"
   5  end
   6  
   7  class Favorite < ActiveRecord::Base
   8    belongs_to :user
   9    belongs_to :favorable, :polymorphic => true
  10    attr_accessible :user, :favorable
  11  end
  12  
  13  class Feed < ActiveRecord::Base
  14    has_many :favorites, :as => :favorable
  15    has_many :fans, :through => :favorites, :source => :user
  16  end
  17  
  18  class Entry < ActiveRecord::Base
  19    has_many :favorites, :as => :favorable
  20    has_many :fans, :through => :favorites, :source => :user
  21  end

The migration:

   1  create_table :favorites do |t|
   2    t.references :user
   3    t.references :favorable
   4    t.string :favorable_type
   5  end

The test:

   1  user.favorite_entries
   2  user.favorite_feeds
   3  
   4  feed.fans
   5  entry.fans

The end.

Tagged rails, favorites, polymorphic