Reputation: 18871
I am using Ruby on Rails 3.2.9. I implemented a custom validator and I would like to skip validations (on creating a new object in a migration file) when using the validate
method. In general I can use :without_protection => true
as a parameter of the create!
method but in my case (see the code below) it seems do not work: validation are not skipped.
class Article < ActiveRecord::Base
validate do
# custom validation code
end
end
How can I skip validations?
Upvotes: 1
Views: 1963
Reputation: 1929
Without protection does not turn off validations, it allows you to mass-assign protected attributes. To save without validating:
new_record = Article.new
new_record.save(:validate => false)
Upvotes: 1
Reputation: 211560
You'll have to ensure that all of the other validations are disabled in order for this to be effective. ActiveRecord cannot selectively disable validations, but can omit them entirely.
For instance:
class Article < ActiveRecord::Base
validate :something,
:if => :validations_are_turned_on?
validate :always
protected
def validations_are_turned_on?
!@validations_disabled
end
end
Tagging any of the non-essential validations with the appropriate :if
condition should work. In this case if @validations_disabled
is not set then all validations will run.
Upvotes: 1