Paul Richter
Paul Richter

Reputation: 11072

Ruby on Rails - Model field filters

This is probably a very obvious question but I can't quite figure it out. Is there such a thing in rails as a field, or model filter? Something similar to the concept of a before_filter in controllers. In my situation, we have "time" information from a form that needs to be formatted and verified before being set. Instead of simply applying a validator on the field and returning an error, I would like to make it as user friendly as possible and make an attempt to properly format the data. For example, it would be nice to put in my model something like:

before_filter :formatTimeField, :only=>[:timeField1, :timeField2...etc]

As it is right now, I need to specify mutators for each of these fields, and this seems a little silly to me.

Any ideas? Please let me know if I've left out some crucial information. Thanks in advance!

Upvotes: 0

Views: 820

Answers (1)

Nuby
Nuby

Reputation: 2386

Check out the documentation for before_validation and the rest of the ActiveRecord callbacks. There are a bunch of calls that get made at various stages in the record creation/modification process:

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

In the case you describe, you could call a before_validation method to try and fix the user's inputs and then validate on that modified data. Thus, if you still can't do anything, you can kick it back to the user for correction.

Also, the RoR Guide has a comprehensive overview of the different hooks: http://guides.rubyonrails.org/active_record_validations_callbacks.html#callbacks-overview.

Hope this helps.

Upvotes: 1

Related Questions