I just added this monkey patch to .has to auto validate associations.
Not 100% convinced it's a good idea, but fixes a pretty major problem
when using dm_nested_attributes.
I also added #save_with_transaction. It seems this is something the
framework should just handle transparently on #save, but I'm not sure of
the best way to approach it.
Commentary appreciated.
Xavier
(also available as a gist https://gist.github.com/714925)
module DataMapper
module Model::Relationship
# By default, when validating a model, any child models will not be
# checked for validation. This means that the following situation can
# occur:
#
# user = User.new(:author => Author.new)
# user.valid? # => false
# user.author.valid? # => false
#
# This monkey patch automatically adds a validation to all associations
# so that both methods in the above example will return false.
Validations
# are only run on dirty models (which includes new models), since clean
# ones are assumed to be valid.
def has_with_validation(cardinality, property, *args)
has_without_validation(cardinality, property, *args)
case cardinality
when 1
validates_with_block property do
val = send(property)
if val && val.dirty? && !val.valid?
[false, "#{property.to_s.titleize} must be valid"]
else
true
end
end
when n
validates_with_block property do
val = send(property)
if val.map(&:valid?).all?
true
else
[false, "#{property.to_s.titleize} must be valid"]
end
end
end
end
alias_method_chain :has, :validation
end
end
module DataMapper
module Resource
# Wrap a transaction around the save, useful when multiple nested
models
# will be saved at the same time.
def save_with_transaction(*args)
ret = nil
transaction do
ret = save(*args)
end
ret
end
end
end
--
You received this message because you are subscribed to the Google Groups
"DataMapper" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/datamapper?hl=en.