I have a form with 3 ActiveRecord fields. One of those fields has kind of goofy, and STATE-DEPENDENT validation requirements. (For example, I only validate the field if the object is being created on a setup wizard form.)
In my POST handler to create the object, I thought I could call errors.add to insert a special error condition
@foo = Foo.new(params[:foo])
if goofy_conditions(params[:foo][:goofy_field])
@foo.errors.add(:goofy_field, "doesn't meet the goofy conditions" )
end
respond_to do |format|
if @foo.save
...
else
... redirect back to form (with error fields hilited)
However, doing @foo.errors.add() in the controller doesn’t seem to do anything… it doesnt prevent the save() if the other fields pass validations.
An alternative is to put a custom validation handler into the model… I know using errors.add(:field, ‘msg’) works fine there… but in that case how can my controller ‘pass’ info to the validator telling it whether or not the field needs to be validated.
That is model logic. Look at custom validations
Then it’ll act just like any other validation.
Edit
You can conditionally validate with the
:ifoption:and in your controller: