I am trying to associate existing records while still being able to add new ones. The following does not work but is pretty close to what I need. How can I accomplish associating existing records and creating new ones?
has_many :comments, :through => :commentings, :source => :commentable, :source_type => "Comment"
accepts_nested_attributes_for :comments, :allow_destroy => true
def autosave_associated_records_for_comments
comments.each do |comment|
if existing_comment = Comment.find_by_fax_and_name(comment.fax, comment.name)
self.comments.reject! { |hl| hl.fax == existing_comment.fax && hl.name == existing_comment.name }
self.comments << existing_comment
else
self.comments << comment
end
end
end
Here is a relevant line of source: https://github.com/rails/rails/blob/v3.0.11/activerecord/lib/active_record/autosave_association.rb#L155
I’ve made a solution, but if you know of a better way to do this please let me know!