ruby-on-railsvalidationtransientattr-accessor

In Rails, is there a way to specify a TYPE you'd like an attr_accessor to be, and validate it using built-in Rails validation?


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).


Solution

  • Neither of the replies quite answer the question. I believe the correct answer to the questions is simply "No". The replies both address potential workarounds to the fact that the answer to the question is "No", and both are valid comments / ideas.