Allow overriding validations - pass :perform_validations => false to save from create_or_update while skipping model validations.

This commit is contained in:
Mike Gunderloy 2009-11-26 10:54:30 -06:00
parent ca4478bbf4
commit 04ce99a506
3 changed files with 24 additions and 3 deletions

7
README
View File

@ -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 If you change your mind about the name for the site administrator, you can just edit the data
and re-run the task. 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 rake tasks
====================== ======================
db_populate includes three rake tasks: db_populate includes three rake tasks:

View File

@ -5,15 +5,20 @@ class ActiveRecord::Base
# If it exists, it is updated with the given options. # 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. # 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. # Returns the record.
def self.create_or_update(options = {}) def self.create_or_update(options = {})
id = options.delete(primary_key.to_sym) id = options.delete(primary_key.to_sym)
validate = options.delete(:perform_validations) || true
record = send("find_by_#{primary_key}", id) || new record = send("find_by_#{primary_key}", id) || new
record.id = id record.id = id
record.attributes = options record.attributes = options
record.save! if validate
record.save!
else
record.save!(false)
end
record record
end end
end end

View File

@ -8,6 +8,7 @@ end
class Customer < ActiveRecord::Base class Customer < ActiveRecord::Base
set_primary_key "cust_id" set_primary_key "cust_id"
validates_length_of :name, :minimum => 4
end end
class DbPopulateTest < Test::Unit::TestCase class DbPopulateTest < Test::Unit::TestCase
@ -46,5 +47,13 @@ class DbPopulateTest < Test::Unit::TestCase
assert_equal c.name, "George" assert_equal c.name, "George"
end 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 end