I have a standard polymorphic relationship and I need to know who its parent is before I save it.
Class Picture < AR::Base
belongs_to :attachable, :polymorphic => true
end
Class Person < AR::Base
has_many :pictures, :as => :attachable
end
Class Vehicle < AR::Base
has_many :pictures, :as => :attachable
end
I’m uploading pictures via Paperclip and I build a processor that needs to do different things to different pictures (ie. the Person pictures should have Polaroid look & the vehicle pictures should have an overlay). My problem is that before the picture is saved I don’t know if it is associated with a Person or a Vehicle.
I tried putting a “marker” in Person & Vehicle so that I could tell them appart, but when I’m in the Paperclip processor the only thing I see is the Picture class. 🙁 My next thought is to climb up the stack to try and get the parent caller but that seems quite smelly to me. How would you do it?
I “solved” this problem and wanted to post it here so that it may help someone else. My solution was to create a “parent” method on the Picture class that climbed up the stack and found something that looked like it’s parent.
WARNING: This is crappy code and should probably not be used under any circumstance. It worked for me, but I can’t guarantee that it wont cause bodily harm sometime down the road.
What this code does is walk up the
callertree looking for a ancestor named*_controller.rb. If it finds one (and it should) then it parses out the name into a class which should be the parent class of the calling code. whewBTW: I dropped Paperclip and started using CarrierWave. It does this sort of thing much more easily and I was able to get it working in half the time. Yea CarrierWave!