I have a before_validation
callback that reformats one of the entries. I need it to run before validation, to be sure, that formatted output was parsed correctly. But as far as I understand each time I call valid?
to check if data is ok, the entry will be reformatted. Can I do this another way, because on valid?
I just want to check if all the fields are valid and not change something.
Asked
Active
Viewed 264 times
1

Uko
- 13,134
- 6
- 58
- 106
1 Answers
2
this looks really similar to this one: Rails model validation on create and update only
You can do
before_validation(:on => :create) do
reformat #method call, not a symbol
end
before_validation(:on => :update) do
reformat #method call, not a symbol
end
but it still runs for me when I call valid?
. Not sure why though, because that's not in the context of creating or updating, so I feel like Rails lies to us in this case.
If you could make it into a before_save
, then it should work, since that runs after validation. You said you need to validate that it's still ok when you reformat, so maybe add a new method to validate the reformatting, and do
before_save :reformat, :validate_reformatting
or add the sanity check at the end of your method that you use to reformat.

Community
- 1
- 1

keithepley
- 4,760
- 3
- 23
- 41
-
This won't work :(. First of all `:on => [:create, :update]` gives an error: `unexpected '[', expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END ... (self.validation_context == :[:create, :update])`, and then I add `:on => :save` the callback method is not being called on `.save` – Uko Jun 15 '12 at 08:09
-
Sorry about that, I didn't read the other topic I mentioned closely enough, and it actually said `:on => [:create, :update]` doesn't work, and `:on => :save` isn't working for me either. I'll update with the correct syntax to do it, but it's still running on `valid?` for me. – keithepley Jun 15 '12 at 15:35