My app has an association that’s got me scratching my head.
I have Users, and Images. A User has many Images. (Yes, another
picture sharing app, but it’s for a small niche, and it doesn’t end
in -r!)
I would like to express a “Favorite” relationship between both Users
to Users, and Users to Images. This seems like the opposite of the
standard polymorphic model, i.e. tags and taggable, where a Tag may
apply to many different types of Thing.
Perhaps I’m not thinking of it properly, but this was my first stab
at the relationship:
###############################################################
class Image < ActiveRecord::Base
Can be a favorite
belongs_to :favorite
belongs_to :favorable, :polymorphic => :true
end
class User < ActiveRecord::Base
has_many :images
Can be a favorite
belongs_to :favorite
belongs_to :favorable, :polymorphic => :true
Has many favorite ‘things’
has_many :favorites, :dependent => :destroy
has_many :favorite_images, :as => :favorable, :through => :favorites,
:classname => “Image”
has_many :favorite_users, :as => :favorable, :through => :favorites,
:classname => “User”
end
class Favorite < ActiveRecord::Base
belongs_to :favorable, :polymorphic => true
end
create_table “favorites” do |t|
t.column :user_id, :integer
t.column :favorable_id, :integer
t.column :favorable_type, :string
end
create_table “images” do |t|
t.column :name, :string
end
create_table “users” do |t|
t.column :name, :string
end
###############################################################
This is of course wrong and does not work But I don’t know
whether I’m thinking of the problem incorrectly, or whether there’s
even a proper way to do this sort of reverse-polymorphic-join in
ActiveRecord.
Does anyone have any advice?
-Seth