I have a 'validate_on_create' statement in one of my controllers that I would like all of my seed data to skip. What are some solutions so that the create statement in my seeds file skips this validation. My current solution is commenting out the validation each time I run rake db:seed. Anything a little more clever?
+3
A:
You can skip validations by calling model.save(false)
on your seeds, assuming you are not loading them via fixtures.
Chubas
2010-05-17 02:26:14
But I am using the create function in the seed file. Are you suggesting I don't?
Jack
2010-05-17 21:38:21
so instead of 'create' use 'build' function
Greg Dan
2010-09-02 22:48:22
it's Rails 3 and it's for one object creation not multiple
KARASZI István
2010-09-03 12:47:11
A:
You can explicitly skip all validations when you save an object by calling object.save(false)
.
For example:
# In your model
def validate_on_create
# An example validation - replace with whatever you like
return true unless name.blank?
end
# In db/seeds.rb
# Create a new person
p = Person.new(:name => 'Bob')
# Save the record to the database, and *skip validation*
p.save(false)
nfm
2010-08-31 22:15:44
I know about that, but I would like to use it with: `Model.create` instead of `Model.save(false)`
KARASZI István
2010-09-01 09:21:43
There's no option to skip validations when you call `object.create`. Why not just call `object.save(false)`?
nfm
2010-09-01 11:34:20
because I'm creating a lot of objects like this:`models = Model.create([{ :name => "First name" }, { :name => "Second name" }])`
KARASZI István
2010-09-03 12:42:41
+1
A:
Have you considered adding an attribute in the model which is checked in the validate_on_create method?
Example:
class MyModel < ActiveRecord::Base
attr_accessor :skip_on_create_validation
def validate_on_create
unless skip_on_create_validation
# do validation
end
end
end
# In db/seeds.rb
MyModel.create(:skip_on_create_validation => true, ......)
Sidane
2010-09-01 21:13:34