Ruby on Rails Monday, January 2, 2012

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, sohow 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!

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment