Friday, January 28, 2011

How can I intercept the mass-assignment hash for an ActiveRecord object and filter it?

Programmer Question

Let's say I have a record class Person with an integer field awesomeness.



If I call Person.new(:awesomeness => 5), it works fine.



If I call Person.new(:awesomeness => 'five'), as expected, Rails does its bets to figure out what 'five' is as an integer and fails, so it just defaults to 0. Can I intervene by intercepting the hash and fidgeting with the data somehow?



The earliest "event" in the ActiveRecord callbacks is the before_save, by which point 'five' has already become 0.



I could obviously do this controller-side, but this seems to be something that belongs strictly in the model as a filter.



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails