I ran across something the other night in Rails 5 using a “belongs to” relationship that I want to share.
Let’s say you have code similar to the following:
This belongs to relationship works fine as long a user has an organization. If you try to save a user and
organization_id is blank, you’d get the error:
Organization can’t be blank. This threw me for a loop. Ruby on Rails has never required this before. A quick Google search shows that using belongs_to now requires an association to be present. This is the default behavior in Rails 5. It makes complete sense, typically our relationships that belong to something rely on the associated record to exist.
This would be the same as:
Keep this in mind when using things like
accepts_nested_attributes_for. It would work fine as long as your form included fields_for an organization. What if you want an organization to be optional, though?
With the new requirement, this will fail without an organization. How do we fix that? It’s pretty simple.
The Optional Belongs To Solution
If you want to hear me share more of my mistakes, sign up here.
Interested in More?
I'm an open book!
Drop me your email 👇🏻 and I'll share posts like this with you as I write them.