Custom Form Models in Rails

If you’re a rails developer you’ve probably tackled forms which update multiple models and have their own custom validations and/or business logic involved. I’m talking about forms like Signup which may need to create a few other models after the User has successfully been saved.

I’ve recently had to build a signup form which would create or organization, then create a new postgres schema for the organization, then build the administrative user model and also capture payment. Doing this with simple after_create calls would most likely wreak havoc later in life so I’ve split this out into a separate Signup model.

I ended up going the Form Model route which is really easy and I think is a really good fit for forms which have one-off custom validation and business logic that you want to keep out of the models. I’m also not a generally a big fan of validates_associated and accepts_nested_attributes_for unless used with extreme caution, and a custom form model saved me having to bind a bunch of models together with callbacks.

Heres a little piece of the code I ended up with. I’ve stripped out some of the payment code and other little pieces to keep it short. The only class of importance is BaseForm - the rest are just standard rails CRUD work.

View Gist