Last active
January 9, 2019 14:32
-
-
Save ThomasSevestre/82cec7ddfb01caa86b8082c3ac238496 to your computer and use it in GitHub Desktop.
ActiveRecord - Partial model validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
# DISCLAIMER - USE AT YOUR OWN RISK | |
# I'm using it with rails from version 4.2.4 to 4.2.6 | |
# | |
# This file can be pasted in app/models/concerns | |
# | |
# This module needs to be included in the model to enable partial validation. | |
# It is designed to make partial validation transparent for the model. | |
# The controller is ... in control ;) | |
# | |
# Usage: | |
# | |
# 1. include the module in the model to enable partial validation | |
# | |
# class MyModel < ActiveRecord::Base | |
# include Concerns::PartialValidation | |
# # write validations as usual | |
# end | |
# | |
# 2. perform partial validation in the controller | |
# | |
# class MyModelController < ApplicationController | |
# # This action performs a partial update, with partial validation | |
# # It will validate updated parameters only. | |
# def update | |
# my_model= MyModel.find(params[:id]) | |
# my_model.assign_attributes(params[:my_model]) | |
# my_model.save(partial_validation: params[:my_model].keys) | |
# end | |
# end | |
# | |
module Concerns | |
module PartialValidation | |
extend ActiveSupport::Concern | |
def valid?(context = nil, partial_validation = nil) | |
context ||= (new_record? ? :create : :update) | |
super(context) | |
if partial_validation | |
(errors.keys - partial_validation).each do |validation_to_skip| | |
errors.delete(validation_to_skip) | |
end | |
end | |
errors.empty? | |
end | |
def perform_validations(options={}) # :nodoc: | |
options[:validate] == false || valid?(options[:context], options[:partial_validation].try!(:map, &:to_sym)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment