couchbase / couchbase-ruby-model

The Active Model implementation for Couchbase Server built on couchbase-ruby-client
61 stars 23 forks source link

Conditional validation fails when calling #persisted? on create #35

Open jschwindt opened 9 years ago

jschwindt commented 9 years ago

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?