Django Forms in Rails

2 min read Original article ↗

JRB

  • 2013-05-23

    Django Forms in Rails

    I really enjoyed watching George’s talk on what we (Rails guys) can learn from Django. If you haven’t watched it, do it, it’s well worth it.

    My favourite part was when he was talking about how forms work in Django, and how they properly respect the single responsibility principle.

    What I especially liked about that part was how familiar it seemed. After working with rails for years and getting sick of attr_accessible, or ever widening public APIs for models to handle extra forms I’d ended up in a very similar place to Django by accident.

    My rule now when building rails apps is that no user facing form is ever allowed to speak directly to a subclass of ActiveRecord::Base, but instead to a specific form model created for that action.

    I still cheat when I’m writing an admin page, because I trust the people I’ve given access to those pages to be good citizens security wise, and the whole point of admin pages (when I write them) it to totally mess with objects beyond what is reasonable anyway.

    Below is the code I use to set up form models. I keep them all in app/models/forms. You might want to organise them differently, but I prefer to keep them together so I can quickly scan through a list of everything that users can directly input into the system.

    You’ll notice in the comments I link off to the Pivotal Labs blog post. I used to do this a different way, but when I saw their blog post ages and ages ago, they were doing it in a much tidier way so I borrowed it :)