Sometime I want all of Rails’ form bells and whistles for something that isn’t a database backed model. For example, I use this as a handy way to get form validations when starting a session with an API.
This is possible because Rails allows you to use ActiveModel without a database.
1 2 3 4 5
This creates a model that has standard Rails validations, responds to
#errors, but blows up if you try to call
Given that model and a form like:
1 2 3 4
I can use this in a controller:
1 2 3 4 5 6 7
If the key and secret are not supplied, @connection won’t be
form_for will do all the usual error display magic.
I can make my model more useful by adding my connection logic inside it:
1 2 3 4 5 6 7 8 9 10 11
and change my controller thusly:
You can do a whole lot more with
ActiveModel::Model, for example
#save to write back to an API. But, that’s another
show. For now, take a look at
Active Model Basics.