How to fix TypeError: Nil is not a Symbol or String

If you’re using the form helpers built into Rails (or a library like SimpleForm that’s built on top of them), you might run into a somewhat confusing error:

TypeError: nil is not a symbol nor a string

Usually this will originate from somewhere like value_for_collection which is part of the FormOptionsHelper in ActionView, but grepping the source won’t yield any results for the error string. You might be experiencing this in your own application you’re using a tiny dose of metaprogramming.

That’s because TypeError comes from Ruby. The actual call raising this error is __send__, which is happening in the Ruby internals after a call to send. In the FormOptionsHelper example case above, value is nil, and Rails tries to call item.send(nil) which won’t work.

If you’re encountering this in your own code this should be easy enough to fix: add a nil guard to ensure the value you’re passing to send is non-nil. If you’re using, say, a grouped_select in SimpleForm, the fix is a little less direct: add a value_method parameter to your call to input:

<%= f.input :flavors, 
            collection: @grouped_flavors,
            as: :grouped_select,
            group_method: :first,
            label_method: :flavor_name,
            value_method: :id %>

This is because SimpleForm isn’t defensive about input, which is fine if you’re developing an application, but less so if you’re developing a library for others to use where a helpful error message can save dozens of people time and confusion. Lesson learned!


Now read this

Exporting an embeddable React component from a Gatsby app using Webpack

A recent project called for the header and footer—implemented as React components in Gatsby—to be embedded on third-party sites (think support documentation). Since both components rely on Gatsby’s Link component as well as its... Continue →