module PowerTools::ActiveRecord::SetAssociationWithHash def association_hash_writer(*associations) unless generated_methods? define_attribute_methods end associations.each do |a| unless respond_to?("#{a}_with_hash_writer=") define_method "#{a}_with_hash_writer=" do |attributes| if attributes.is_a?(Hash) if existing = send("#{a}") existing.update_attributes(attributes) else send "build_#{a}", attributes end else send "#{a}_without_hash_writer=", attributes end end alias_method_chain "#{a}=", :hash_writer end end end end