Awesome polymorphic goodness in before_create

This isn’t a question – it’s just me being astonished by yet another
thing in Rails that Just Works. Here it is:

class Wizard < ActiveRecord::Base
before_create :create_deferrables
has_one :weather_loader, :as => :owner, :dependent => :destroy

def create_deferrables
self.create_weather_loader
end

end

class WeatherLoader < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
end

I’d always assumed the above would NOT work because
Wizard#create_weather_loader gets called before the wizard had been
assigned an id, so how would WeatherLoader#owner_id get set?

And yet the architecture of relations is smart enough to know that when
it assigns an ID to the wizard that it needs to update the
weather_loader as well. (And since it’s a polymorphic association, it
automagically sets WeatherLoader#owner_type as well.)

IMHO, that’s chunky-bacon awesomeness. Thank you, Rails!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs