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?