Rails Polymorphic Association with multiple associations on the same model
Posted
by Matt Rogish
on Stack Overflow
See other posts from Stack Overflow
or by Matt Rogish
Published on 2010-03-22T17:41:48Z
Indexed on
2010/03/22
20:21 UTC
Read the original article
Hit count: 394
rails
|polymorphic-associations
My question is essentially the same as this one: http://stackoverflow.com/questions/1168047/polymorphic-association-with-multiple-associations-on-the-same-model
However, the proposed/accepted solution does not work, as illustrated by a commenter later.
I have a Photo class that is used all over my app. A post can have a single photo. However, I want to re-use the polymorphic relationship to add a secondary photo.
Before:
class Photo
belongs_to :attachable, :polymorphic => true
end
class Post
has_one :photo, :as => :attachable, :dependent => :destroy
end
Desired:
class Photo
belongs_to :attachable, :polymorphic => true
end
class Post
has_one :photo, :as => :attachable, :dependent => :destroy
has_one :secondary_photo, :as => :attachable, :dependent => :destroy
end
However, this fails as it cannot find the class "SecondaryPhoto". Based on what I could tell from that other thread, I'd want to do:
has_one :secondary_photo, :as => :attachable, :class_name => "Photo", :dependent => :destroy
Except calling Post#secondary_photo simply returns the same photo that is attached via the Photo association, e.g. Post#photo === Post#secondary_photo. Looking at the SQL, it does WHERE type = "Photo" instead of, say, "SecondaryPhoto" as I'd like...
Thoughts? Thanks!
© Stack Overflow or respective owner