Skip to content

Instantly share code, notes, and snippets.

@albb0920
Created August 15, 2012 17:29
Show Gist options
  • Save albb0920/3361786 to your computer and use it in GitHub Desktop.
Save albb0920/3361786 to your computer and use it in GitHub Desktop.
update or create nested association
class Book < ActiveRecord::Base
attr_accessible :authors_attributes
has_and_belongs_to_many :authors
accepts_nested_attributes_for :authors
def authors_attributes=(new_authors)
self.authors = new_authors.collect do |author_attrs|
if author_id = author_attrs.delete(:id)
author = Author.find(author_id) rescue nil
end
# new author or bad author_id
author = Author.new unless author
author.attributes = author_attrs
author
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment