Created
December 23, 2013 16:16
-
-
Save mmrwoods/8099794 to your computer and use it in GitHub Desktop.
Skip validation of associated objects unless nested attributes have been provided
This file contains hidden or 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
module ActiveRecord | |
module NestedAttributes | |
module ClassMethods | |
# Skips validation of associated objects unless nested attributes have been provided. | |
# | |
# This is a horrid workaround for the fact that nested_attributes_for sets the autosave | |
# option for each assocation to true, which causes validation to fail for associated | |
# objects that have been loaded, whether any nested attributes have been provided or not. | |
# This causes problems with the parent object is updated from forms that don't include | |
# the nested attributes, and therefore don't allow the validation errors to be rectified. | |
# | |
# Note: at the moment, this method does too much - it also creates an attribute reader | |
def skip_validation_unless_attributes_provided_for(*attr_names) | |
attr_names.each do |association_name| | |
# attr_reader :pirate_attributes | |
# alias_method :assign_pirate_attributes, :pirate_attributes= | |
# def assign_and_record_pirate_attribues(attributes) | |
# @pirate_attributes = attributes | |
# assign_pirate_attributes(attributes) | |
# end | |
# alias_method :pirate_attributes=, :assign_and_record_pirate_attribues | |
# before_validation do | |
# if self.pirate_attributes.nil? | |
# class << self.agency | |
# def valid? ; true ; end | |
# end | |
# end | |
# end | |
class_eval <<-eoruby, __FILE__, __LINE__ + 1 | |
attr_reader :#{association_name}_attributes | |
alias_method :assign_#{association_name}_attributes, :#{association_name}_attributes= | |
def assign_and_record_#{association_name}_attribues(attributes) | |
@#{association_name}_attributes = attributes | |
assign_#{association_name}_attributes(attributes) | |
end | |
alias_method :#{association_name}_attributes=, :assign_and_record_#{association_name}_attribues | |
before_validation do | |
if self.#{association_name}_attributes.nil? | |
class << self.#{association_name} | |
def valid?(context = nil) ; true ; end | |
end | |
end | |
end | |
eoruby | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment