Reputation: 548
I'm trying to selectively enforce validations on a model. I want the model to enforce them when data is entered from users, but when running files in I want to ignore the validations sometimes. I came up with the less then intelligent method of setting a boolean to TRUE when adding from the web user. Seemed great until I need to update from the file and now I basically have to switch the boolean on all the records. Here is some of my code:
class Identity < ActiveRecord::Base
validate :validate_spouse_age, :if => "web_add?"
validates :ssn, length: { is: 9 }
def validate_spouse_age
if (relationship == "S" || relationship == "DP") && !dob.nil? && web_add? && age<16
errors.add(:dob, :spouse_under_age)
end
true
end
end
So on the web form I just add a hidden_fiedl setting 'web_add' to true and the validation runs and that gets saved to the record. But now when I want to run the following I have to set the boolean back to false or the validation will still run.
identity.web_add=false #to allow it to be updated without validation fails
identity.update_attributes!(
namefirst: line.FIRST_NAME,
namelast: line.LAST_NAME
)
I'm sure there is a smarter way to do this. Why I'm not just ignoring the validation completely is there are some validations that I want to run regardless of the data source. For example, the SSN needs to be there or it should fail out.
Any help would be more then appreciated!!!
Upvotes: 1
Views: 113
Reputation: 9308
You can skip the entire 'web_add' boolean and use the update_attribute
method in your non-web method. You will need to update each attribute individually, but it will skip the validations and commit the changes to the database. You could implement something like:
instance.update_attribute(name, value)
in your case
identity.update_attribute(:namefirst, line.FIRST_NAME)
identity.update_attribute(:namelast, line.LAST_NAME)
When a web user submits a form, the validations will run normally. When you run the update_attribute
method, the validations will be skipped.
Here's a list of all the methods available to skip activerecord validations:
decrement!
decrement_counter
increment!
increment_counter
toggle!
touch
update_all
update_attribute
update_column
update_counters
Upvotes: 1