Partial model validation

Hello,

I’ve been looking for a solution to perform partial validation of a model.
This is often an issue when you have multiple forms to fill a single model (ie with wicked wizard gem).
They are multiple complicated solutions on the web but it would be fairly easy to implement inside the validation framework.

I can provide a patch if interested.

This could be the API:

my_object.save(partial_validation: array_of_attributes_to_validate)

The modified functions of active_record/validations (on branch 4.2)

def valid?(context = nil, partial_validation = nil)
  context ||= (new_record? ? :create : :update)
  output = super(context)
  if partial_validation
    (errors.keys - partial_validation).each do |attr|
      errors.delete(attr)
    end
  end
  errors.empty? && output
end

def perform_validations(options={}) # :nodoc:
  options[:validate] == false || valid?(options[:context], options[:partial_validation].map(&:to_sym))
end

Let me know if interested

Regards,
Thomas

You can use the context param or a “form object” if you only need to do partial validations.

The context param is ok for some cases, ie for implementing a state machine like the business logic of an order.

But in my opinion the model should not change wether it is edited in a single form or in a wizard. You should not need to edit the model when you move an input field from a view to anther… This should be handled in the controller. With the proposed patch :

def uptade
  ...
  my_object.assign_attributes(params)
  my_object.save(partial_validation: params.keys)
  ...
end

Done !

Let me know if you are interested with a PR

I Not sure if you saw or not, I have docs for how to cobble this together with existing pieces. https://github.com/schneems/wicked/wiki/Building-Partial-Objects-Step-by-Step



Yes I saw it, there is also this solution:
https://gist.github.com/kizzx2/4722784

I’ve published my current solution here:
https://gist.github.com/ThomasSevestre/82cec7ddfb01caa86b8082c3ac238496