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.
-- 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?
The before_validation callback allows restrictions to particular events within the lifecycle of an object. Here is the documentation of this option for Rails 4.0, Rails 5.2, Rails 6.0 and Rails 7.0.
Rails provides before and after actions in controllers as an easy way to call methods before or after executing controller actions as response to route requests. Action Callbacks can be particularly helpful when implementing authentication/authorization for example, and are heavily used by gems such as Devise.
Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
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?
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