I've never been able to find a nice way to do this, so I thought I'd ask.
For example, in an ActiveRecord model, database backed attributes are automatically type-converted to the appropriate database-backed types. If I have a Category
model, and it has a couple of attributes, say name
and category_id
, if I go like this:
Category.new(params[:category])
Rails knows that name
is a String and category_id
is an Integer.
Let's say I have several transient/synthetic attributes that I want to validate, and they have specific types. I want to submit them from a form, and I'd like them to be automatically converted to either a String or an Integer or a Date (for example) based on how they're defined.
If I was to declare something in a Rails model like:
attr_accessor :some_number_variable
attr_accessor :some_date
Is there a built-in way to tell Rails "I'd like you to cast the former to an Integer and the latter to a Date, when I go Category.new(params[:category])
" so long as params[:category][:some_number_variable]
and params[:category][:some_date]
are part of the data submitted to the controller (I realize the Date example might be a bit trickier given the many date formats out there).