Created
January 8, 2009 23:05
-
-
Save cjbottaro/44937 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person < ActiveRecord::Base | |
has_many :addresses | |
validates_associated :addresses | |
validates_length_of :addresses, :less_than => 5 | |
before_save :save_addresses | |
def addresses_from_form=(address_hashes) | |
addresses = address_hashes.collect{ |address_hash| Address.new(address_hash) } | |
self.addresses.target = addresses # sets the association target, doesn't trigger any saves or destroys | |
# this works because validates_associated basically just does self.addresses.each{ |address| address.valid? } | |
# so the net effect is that validation happens on these new, unsaved addresses, so if validation fails, the database is untouched | |
end | |
def save_addresses | |
# validation has passed, so it's time to save those addresses | |
if addresses.all?{ |address| address.new_record? } | |
temp = addresses.to_a | |
addresses.reload(true).each{ |address| address.destroy } | |
addresses = temp # that should trigger the saving | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment