lib/seed-fu/seeder.rb in seed-fu-2.0.0 vs lib/seed-fu/seeder.rb in seed-fu-2.0.1.rails31

- old
+ new

@@ -30,13 +30,15 @@ end # Insert/update the records as appropriate. Validation is skipped while saving. # @return [Array<ActiveRecord::Base>] The records which have been seeded def seed - @model_class.transaction do + records = @model_class.transaction do @data.map { |record_data| seed_record(record_data.symbolize_keys) } end + update_id_sequence + records end private def validate_constraints! @@ -57,21 +59,36 @@ end def seed_record(data) record = find_or_initialize_record(data) return if @options[:insert_only] && !record.new_record? - record.send(:attributes=, data, false) + puts " - #{@model_class} #{data.inspect}" unless @options[:quiet] - record.save(:validate => false) + + record.send(:attributes=, data, false) + record.save(:validate => false) || raise(ActiveRecord::RecordNotSaved) record end def find_or_initialize_record(data) @model_class.where(constraint_conditions(data)).first || @model_class.new end def constraint_conditions(data) Hash[@constraints.map { |c| [c, data[c.to_sym]] }] + end + + def update_id_sequence + if @model_class.connection.adapter_name == "PostgreSQL" + quoted_id = @model_class.connection.quote_column_name(@model_class.primary_key) + quoted_sequence = "'" + @model_class.sequence_name + "'" + @model_class.connection.execute( + "SELECT pg_catalog.setval(" + + "#{quoted_sequence}," + + "(SELECT MAX(#{quoted_id}) FROM #{@model_class.quoted_table_name}) + 1" + + ");" + ) + end end end end