Jason Charnes

Belongs to Is Now a Required Association in Rails 5

I ran across something the other night in Rails 5 using a “belongs to” relationship that I want to share.

The Problem

Let’s say you have code similar to the following:

class Organization < ApplicationRecord
has_many :users
end
 
class User < ApplicationRecord
belongs_to :organization
end

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 <em>can't be blank</em>. 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:

class Organization < ApplicationRecord
has_many :users
end
 
class User < ApplicationRecord
belongs_to :organization
validates :organization, presence: true
end

Keep this in mind when using things like <em>accepts_nested_attributes_for</em>. It would work fine as long as your form included fields_for an organization. What if you want an organization to be optional, though?

class Organization < ApplicationRecord
has_many :users
end
 
class User < ApplicationRecord
belongs_to :organization
accepts_nested_attributes_for :organization, reject_if: :all_blank
end

With the new requirement, this will fail without an organization. How do we fix that? It’s pretty simple.

The Optional Belongs To Solution

class User < ApplicationRecord
belongs_to :organization, optional: true
end
Follow me on Twitter.