Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can a controller manually set validation errors for a certain field

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.

like image 695
jpw Avatar asked Oct 02 '12 00:10

jpw


1 Answers

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
like image 66
bricker Avatar answered Oct 10 '22 12:10

bricker