'to_f or not to_f', that is the matter of my question...

What is the best practice for handling ActiveRecord attributes in logic when those attributes were allowed to be nil? I've been handling the possibly-nil status of my Numeric attributes in my logic by calling to_f (to_i) on them, but I wonder if there's a better practice? For example, default values could be set in the migration or validations could set blank fields to a default.

Any suggestions on the best practice in this case?

Thanks,

Grar

If you are treating nil as effectively 0.0 rather than no value then I think there is a good argument for setting a default value, and not allowing null in the db.

If you need to distinguish nil as being 'no value' which is different from 0.0 then you cannot use a default value.

Colin

Colin,

So, there is something I will regret either in terms of i) db performance or ii) db maintenance by not using default float (int) defaults where appropriate?

My view of the tradeoff was: 1) coding defaults to the attributes in a migration vs. 2) calling to_f (to_i)on them in logic.

With no previous experience in the matter, I'll adopt your proposal.

Thanks,

Grar

Grary Stimon wrote:

So, there is something I will regret either in terms of i) db performance or ii) db maintenance by not using default float (int) defaults where appropriate?

My view of the tradeoff was: 1) coding defaults to the attributes in a migration vs. 2) calling to_f (to_i)on them in logic.

Personally, I see no "tradeoff" here.

This is a matter of business logic. You want the column to either (a) always have a specified rational value or (b) allow the value to be unspecified.

I believe that most would agree that setting constraints NOT NULL DEFAULT 0.0 would be the most reliable method for implementing (a) in a RDBMS.

But, whatever technique you use to disallow NULL values in the database is a matter of business logic, regardless of any other considerations, such as performance or convenience.

Colin,

So, there is something I will regret either in terms of i) db performance or ii) db maintenance by not using default float (int) defaults where appropriate?

My view of the tradeoff was: 1) coding defaults to the attributes in a migration vs. 2) calling to_f (to_i)on them in logic.

Sorry I don't understand what you are saying here about there being a tradeoff.

Colin

Having duly considered it, I withdraw my suggestion of a 'tradeoff'.

I'm better off for your comments, so thanks all.

Grar