Skip to content

Instantly share code, notes, and snippets.

@rwc9u
Created June 21, 2011 20:07
Show Gist options
  • Save rwc9u/1038757 to your computer and use it in GitHub Desktop.
Save rwc9u/1038757 to your computer and use it in GitHub Desktop.
:accepts_nested_attributes_for with custom autosave
class Address < ActiveRecord::Base
has_many :phonings, :as => :phonable
has_many :phone_numbers, :through => :phonings
accepts_nested_attributes_for :phonings, :allow_destroy => true
end
class Person < ActiveRecord::Base
has_many :phonings, :as => :phonable
has_many :phone_numbers, :through => :phonings
end
class Phoning < ActiveRecord::Base
belongs_to :phone_number, :autosave => true
belongs_to :phonable, :polymorphic => true
accepts_nested_attributes_for :phone_number
def autosave_associated_records_for_phone_number
if new_phone_number = PhoneNumber.where(:phone_number => phone_number.phone_number).first then
self.phone_number = new_phone_number
else
self.phone_number.save!
self.phone_number_id = self.phone_number.id
end
end
end
class PhoneNumber < ActiveRecord::Base
has_many :phonings, :dependent => :destroy
has_many :addresses, :through => :phonings, :source => :phonable, :source_type => "Address"
has_many :people, :through => :phonings, :source => :phonable, :source_type => "Person"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment