MilesStanfield
MilesStanfield

Reputation: 4639

Validate no other record exists without querying the db table

I'm trying to figure out if it's possible to write a rails activerecord validation that validates this new record will be the first and only record in the db table WITHOUT an additional query to the db in the validation.

class Foo < ActiveRecord::Base      
  validate :first_and_only_foo?
  validates :name, uniqueness: true

  def first_and_only_foo?
    errors.add(:base, "another foo already exists") if something_that_doesnt_query_db
  end
end

So doing that ^ without any of this in the validation ...

MyTable.first.present?

Any ideas?

I've read through the docs on validations (maybe i missed something) but I don't see anything that would pertain to this usecase.

If there's some validates :name way of going about this I'd be interested to know what that might be.

Upvotes: 0

Views: 359

Answers (1)

Mohamad
Mohamad

Reputation: 35349

There's a uniqueness validation, but it will perform a query under the hood. What you are suggesting does not exist in Rails out of the box. There is a lifecycle of events in ActiveRecord that takes place when you create or update an object, and validations are just one part (initialization, validations, callbacks, etc...).

You can write a method that would rescue a database uniqueness constraint, but I honestly don't know why you would want to do that. The added complexity is not worth it.

Upvotes: 1

Related Questions