Skip to content

mgidea/with_existing_records

Repository files navigation

WithExistingRecords

defines a method to override the generated method from an accepts_nested_attributes_for declaration to take into account when attempting to add existing records onto a collection association. This method checks for the #{association_name}_attributes in params hash and then uses #{association_name}_ids as with the given ids to add them as a collections and then iterates through the model.#{association_name} collection and assigns the model of each association to the parent object. This then lets nested_attributes run its course on save and update. It is best to run save in an ActiveRecord transaction to keep the integrity of the objects. The method also checks to see if the associated object has been deleted on the form as opposed to marked for destruction.

Class User < ActiveRecord::Base
  has_many :addresses, :inverse_of => :user
  accepts_nested_attributes_for :addresses
  add_existing_records_to_nested_attributes_for :addresses
  # - or - more simply -
  nested_attributes_with_existing_records_for(:addresses)
end

Class Address < ActiveRecord::Base
  belongs_to :user, :inverse_of => :addresess
end

This project rocks and uses MIT-LICENSE.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published