“OMFG!” Rails moments – #22

As a Laravel exploring the Rails ecosystem for the first time, I can’t help but compare the two frameworks endlessly. Sure, Laravel took pretty much every concept straight out of the Rails playbook, but there are several small differences that, when combined, show you why Rails is still the granddaddy of all full-stack web frameworks.

This post is about one such “OMFG!” moment.

Let’s talk about data validation — one of the biggest bugbears of full-stack development. It’s a massive chore because you must:

  • Validate on the front-end
  • Validate on the back-end
  • Make sure the validations match, especially when changes are made
  • Produce helpful error messages

That is back-breaking, soul-sapping work if you were to do it all by hand. So, it’s berry nice that our full-stack frameworks all ship with validation engines.

Now, for the really important question: where do you stick the validation code?

Laravel thinks that since the incoming request carries all the data, validation is canonically best done on the request variable, in the controller method (yes, you can do it in a separate request class altogether but let’s not turn a discussion into a turd pile):

public function createPost()
    $validatedData = $request->validate([
        'title' => 'required',
        'body' => 'required',

And, now, the Rails way:

class Topic < ApplicationRecord
    validates_presence_of :title, :body

Amazing! 😍😍

With far less typing, we were able to the same effect, and it reads so elegantly that you need to be extra careful not to fall in love! Although in some ways I prefer the Laravel approach — data is part of the incoming request and should be validated there; also, Larave’s approach is more explicit (that is, it is happening exactly where you’d expect it to happen when you’re reading the code).

Ruby is an artistic language, and Rails is a great example of that art. You may not choose Rails at the end of the day, but you can’t deny its elegance!