# Assigning wrong data type to attribute: how to trap error

**URL:** <https://www.ruby-forum.com/t/assigning-wrong-data-type-to-attribute-how-to-trap-error/127265>\
**Category:** Rails\
**Created:** [January 27, 2008, 1:16pm UTC](https://www.ruby-forum.com/t/assigning-wrong-data-type-to-attribute-how-to-trap-error/127265 "2008-01-27T13:16:02Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kip](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/8e7dd6/32.png) [@Kip](https://www.ruby-forum.com/u/Kip)\
**Post date:** [January 27, 2008, 1:16pm UTC](https://www.ruby-forum.com/t/assigning-wrong-data-type-to-attribute-how-to-trap-error/127265/1 "2008-01-27T13:16:02Z")

</div>

A model has only one column, a numeric and the class definition has no  
constraints define.:

create\_table "examples"do |t|  
t.integer “numberid”  
end

in IRB I create a row, save it, and then attempt to assign “abcd” to  
the attribute. Clearly this is wrong, and in fact the assignment does  
not take place. I would like however to trap this error, which I  
cannot seem to do. Example below:

> > t = Example.create(:numbid =\> 4)  
> > =\> #\<Example id: 3, numberid: 4\>
> 
> > t.numberid = “mmmm”  
> > =\> “mmmm”
> 
> > t.numberid  
> > =\> 0
> 
> > t.numberid\_before\_type\_cast  
> > =\> “mmmm”
> 
> >

Is there a configuration option to make this kind of assignment  
“noisy” in some way so I can trap the error and provide a meaningful  
message to the user?

Thanks for any help,

–Kip

---

<div class="post-metadata">

**Author:** ![Kip](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/8e7dd6/32.png) [@Kip](https://www.ruby-forum.com/u/Kip)\
**Post date:** [January 27, 2008, 2:28pm UTC](https://www.ruby-forum.com/t/assigning-wrong-data-type-to-attribute-how-to-trap-error/127265/2 "2008-01-27T14:28:00Z")

</div>

you can add validations to your model.

---

<div class="post-metadata">

**Author:** ![Kip](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/8e7dd6/32.png) [@Kip](https://www.ruby-forum.com/u/Kip)\
**Post date:** [January 27, 2008, 10:03pm UTC](https://www.ruby-forum.com/t/assigning-wrong-data-type-to-attribute-how-to-trap-error/127265/3 "2008-01-27T22:03:00Z")

</div>

Thanks Sean, I understand that and do it. Just surprised to find that  
the actual assignmnent doesn’t fail, and does return the bogus value  
as the result of the assignment.

So to error processing: my validation message string is:  
“Must be a number between -180 and 180, not  
‘#{self.latitude\_before\_type\_cast}’”

However it appears that the \*\_before\_type\_cast methods (indeed any  
attribute methods) aren’t available in the scope of validations. Any  
ideas how to access these methods in the message string? Or  
alternative suggestions on how to achieve the objective of having a  
meaningful message including the wrong text?

Regards, --Kip
