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
class GoofyThing < ActiveRecord::Base
validate :goofy_attribute_is_goofy
def goofy_attribute_is_goofy
if goofy_conditions(self.goofy_field)
self.errors.add(:goofy_field, "doesn't meet the goofy conditions" )
end
end
end
Then it'll act just like any other validation.
Edit
You can conditionally validate with the :if
option:
attr_accessible :via_wizard
validate :goofy_attribute_is_goofy, :if => lambda { self.via_wizard }
and in your controller:
class WizardController < ApplicationController
before_filter :get_object, :set_wizard
#...
def get_object
@object = GoofyThing.find(params[:id])
end
def set_wizard
@object.via_wizard = true
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With