How a controller can manually set validation errors for a specific field

I have a form with 3 ActiveRecord fields. One of these fields has its own stupidity and requirements for checking STATE DEPENDENCE. (For example, I only check a field if an object is created in the form of a setup wizard.)

In my POST handler to create an 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, executing @ foo.errors.add () on the controller does not seem to do anything ... it does not prevent saving () if other fields pass validation.

An alternative is to install a special validation handler in the model ... I know that using errors.add (: field, 'msg') works fine ... but in this case, how can my controller pass information to the validator, indicating whether check this field.

+7
source share
1 answer

This is model logic. See user checks

 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 will act just like any other check.

Edit

You can conditionally check with the option :if :

 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 
+12
source

All Articles