7

I have a Service model/table and its registration form.

In the form I have almost all the Service's fields, but some of them I want to set a value, automatically, before validate the service object.

  • Example:

-- Service Controller # create Action:

def create
  @service = Service.new
  @service_form = ServiceFormObject.new(@service)

  @service_form.validate(params[:service_form_object]) and @service_form.save
  respond_with(@service_form, location: admin_services_path)
end

Before the @service_form object be validated I want to the @service_form duration_in_hours field be set. So I tried with that code:

-- Service Model:

# Callbacks
  before_validation :set_duration

# Instance methods
private
  def set_duration
    self.duration_in_hours = (self.end_at - self.start_at) / 3600
  end

But the set_duration method didn't run (I put the 'byebug' gem to see if the method ran).

I think that the problem is that I create the form with form object (+ reform gem): i'm using form object to validate the service fields, intsead validate inside Service model.

class ServiceFormObject < BaseFormObject

The BaseFormObject inherit from Reform::Form:

class BaseFormObject < Reform::Form

I tried to put the before_validation and the method inside ServiceFormObject class, but I got an error: undefined method `before_validation' for ServiceFormObject:Class

How can I use before validation callback with form object in Rails 4?

imtk
  • 1,510
  • 4
  • 18
  • 31
  • 3
    `before_validation` is an `ActiveRecord::Callback` and your objects are only inheriting from the Reform gem. – Anthony Jan 07 '15 at 19:56

1 Answers1

11

That means that your ServiceFormObject does not include validation callbacks.

Assuming that Reform::Form does handle ActionModel validations (it includes ActionModel::Validations), I'd try to include the ActiveModel::Validations::Callbacks module into your ServiceFormObject, or even better, into your BaseFormObject:

class BaseFormObject < Reform::Form
  include ActiveModel::Validations::Callbacks

  #...
end

Can you try this out?

dgilperez
  • 10,716
  • 8
  • 68
  • 96