Allow overriding validations - pass :perform_validations => false to save from create_or_update while skipping model validations.
This commit is contained in:
parent
ca4478bbf4
commit
04ce99a506
7
README
7
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:
|
||||
|
@ -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
|
@ -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
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user