Cristopher
Cristopher

Reputation: 323

validate ActiveRecord field with especific class

I want to validate that my field is from an especific class.

Concrete example. I have a model that must by unique by day. So, I insert a validation

validates :my_date_field, uniqueness: {scope: [:scope_one, :scope_two]}

If I create my record with a Date, the validation works fine. If I create my record with a Time, however, (my tests use Time::now) it parses it to a Date, but does not trigger the validation.

How should I fix it?

Thanks in advance.

--Edit-- A related problem:

How I forbid someone to do MyModel::create my_date_field: 4

? It is passing the validate_presence from active_record, passing the null: false from migration, and saving an ugly 4 in my date_field.

I'm completely lost here =\

Upvotes: 0

Views: 77

Answers (1)

Jim Stewart
Jim Stewart

Reputation: 17323

ActiveRecord will type-cast your values to whatever type it thinks is appropriate for the underlying database field. You can still access the original type, though, via my_date_field_before_type_cast. The *_before_type_cast accessors exist for every attribute. There you can check the class or do any other conversions you might need. These are available in custom validation methods as well.

Upvotes: 1

Related Questions