couchbase-ruby-model icon indicating copy to clipboard operation
couchbase-ruby-model copied to clipboard

Conditional validation fails when calling #persisted? on create

Open jschwindt opened this issue 10 years ago • 0 comments

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:

  def persisted?
    !!(meta && meta['cas'])
  end

I could create a PR for this, what do you think?

jschwindt avatar Apr 03 '15 22:04 jschwindt