Wrap Parameters Without Changing Markup

While updating logic that caused a POST with a JSON body to change into a POST as multipart/form-data, I ran into an issue where the Rails controller was expected params in a nested way. Sure, I could change my inputs to have a different name that would cause the nested structure, but that was changing logic down the line.

Rails was wrapping the incoming parameters automatically since the prior request was of 'Content-Type': 'application/json'. Well, I'd really like this same behavior on my new request as it would solve my current conundrum.

Turns out ActionController has a method that can help out with that… the aptly named wrap_parameters method.

In my case, the name I needed was the same as the controller so I could use this:

class FooController < ApplicationController
  wrap_parameters format: %i[mutlipart_form json]

This produces a params payload like so:

ActionController::Parameters {
Continue reading "Wrap Parameters Without Changing Markup"

Query for NULL ‘or’ empty string in ActiveRecord

Sometimes you come across a query that looks for an attribute that is NULL 'OR' an empty string. Sure there are options we could employ that may remove the necessity of checking for both but let's see how we can improve our code a bit first!

The majority of the time I see this as a SQL fragment in ActiveRecord:

Foo.where("name is null or name = ''")

Which produces the following SQL:

SELECT * FROM "foos" WHERE (name is null or name = '')

Sure you can say now that ActiveRecord has or it could be done like so:

Foo.where(name: nil).or(name: '')

However, I'm currently in a project that doesn't support or yet so I went playing to see what I could come up with that wouldn't be a SQL fragment. My first thought was to

Continue reading “Query for NULL ‘or’ empty string in ActiveRecord”

Case Studies in Apprenticeship Vol. 5 –  Matt Polito

Hey Everyone, I found a use for a Singleton