diff --git a/README b/README index 97610ff..ba32c9b 100644 --- a/README +++ b/README @@ -49,6 +49,13 @@ Permission.create_or_update(:id => 1, :role_id => role.id, :user_id => user.id) If you change your mind about the name for the site administrator, you can just edit the data and re-run the task. +By default, create_or_update validates the data (using your model's validations) to ensure that +the data in the database is good. You can turn off validations by passing :perform_validations => false as one +of the parameters to create_or_update: + +user = User.create_or_update(:id => 1, :login => "admin", :email => "BOGUS", + :name => "Site Administrator", :password => "admin", :password_confirmation => "admin", :perform_validations => false) + db_populate rake tasks ====================== db_populate includes three rake tasks: diff --git a/lib/create_or_update.rb b/lib/create_or_update.rb index 374900a..1e40311 100644 --- a/lib/create_or_update.rb +++ b/lib/create_or_update.rb @@ -5,15 +5,20 @@ class ActiveRecord::Base # If it exists, it is updated with the given options. # # Raises an exception if the record is invalid to ensure seed data is loaded correctly. - # + # Pass :perform_validations => false to skip validations in the model. + # # Returns the record. def self.create_or_update(options = {}) id = options.delete(primary_key.to_sym) + validate = options.delete(:perform_validations) || true record = send("find_by_#{primary_key}", id) || new record.id = id record.attributes = options - record.save! - + if validate + record.save! + else + record.save!(false) + end record end end \ No newline at end of file diff --git a/test/db_populate_test.rb b/test/db_populate_test.rb index 36abf7f..bf390cc 100644 --- a/test/db_populate_test.rb +++ b/test/db_populate_test.rb @@ -8,6 +8,7 @@ end class Customer < ActiveRecord::Base set_primary_key "cust_id" + validates_length_of :name, :minimum => 4 end class DbPopulateTest < Test::Unit::TestCase @@ -46,5 +47,13 @@ class DbPopulateTest < Test::Unit::TestCase assert_equal c.name, "George" end + def test_creates_new_record_without_validation + Customer.delete_all + Customer.create_or_update(:cust_id => 1, :name => "Me") + assert_equal Customer.count, 1 + c = Customer.find(:first) + assert_equal c.name, "Me" + end + end