Mark Bolusmjak
Mark Bolusmjak

Reputation: 24409

ActiveRecord attribute_present? lies. How can I fix it?

The docs for attribute_present? say:

Returns true if the specified attribute has been set by the user or by a database load ...

BUT... that's not true! We see here that Rails initializes attributes on a new object from database defaults.

So, suppose we have a users table with age not null default 0. Then

User.new.attribute_present?(:age) == true

But it hasn't been set by us OR a database load.

Perhaps I'm arguing semantics, but in any case, I'd like a method that does what it says: tells me if a field has been explicitly set.

e.g.

u = User.new
# u.attribute_set?(:age) == false
u.age = u.age #set explicitly to default, for example
# u.attribute_set?(:age) == true

Does that exist?

Upvotes: 0

Views: 78

Answers (1)

ilan berci
ilan berci

Reputation: 3881

As far as I know, there isn't a way (provided you have default arguments in your db) (as is good design)

Edited: edited from original answer based on Z5h's comments below

Upvotes: 1

Related Questions