Skip to content

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

Description

@jschwindt

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?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions