0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. Since it's not possible, i realized my code above wouldn't really work anyways because the validate I wrote prevents a record from being updated which wasn't desired. I would need to have used a before_create instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.