Created
August 15, 2012 17:29
-
-
Save albb0920/3361786 to your computer and use it in GitHub Desktop.
update or create nested association
This file contains 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 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