I'd like to add a conditional validation that allows me to create a record without a required field, but become required for subsequent savings, for example:
class User < Couchbase::Model
attribute :name
attribute :email
validates_presence_of :email, if: Proc.new{ |u| u.persisted? }
end
The problem I find is that #persisted? works by checking the presence of the @id which is created just before the validations are checked, so the conditional validation always fails if I want to create a record without the email field.
I think the solutions is to call #valid? before creating the id:
def create(options = {})
if respond_to?(:valid?) && !valid?
return false
end
@id ||= Couchbase::Model::UUID.generator.next(1, model.thread_storage[:uuid_algorithm])
.........
end
Or perhaps a better solution would be to modify #persisted? to check for the presence of @meta['cas'] like this:
I'd like to add a conditional validation that allows me to create a record without a required field, but become required for subsequent savings, for example:
The problem I find is that
#persisted?
works by checking the presence of the@id
which is created just before the validations are checked, so the conditional validation always fails if I want to create a record without theemail
field.I think the solutions is to call
#valid?
before creating theid
:Or perhaps a better solution would be to modify
#persisted?
to check for the presence of@meta['cas']
like this:I could create a PR for this, what do you think?