Ruby, Web Development

Rails 5 – Self Join belongs_to – entity must exist error

Wow, this is my first post for Ruby on Rails and Ruby in general! So what I’m trying to do is very simple: create a self join relationship for the user table like a parent/child relationship. However, Rails always complains about the missing parent even if the relationship is optional (my assumption).

Very simple, common use case

I followed this guide http://guides.rubyonrails.org/association_basics.html and below is my sample code:

class User < ApplicationRecord
  has_many :sub_merchants, class_name: 'User', foreign_key: 'parent_id'
  belongs_to :parent, class_name: 'User'
end

and the table columns:

User:
- id
- parent_id
- email
- password
- created_at
- updated_at

As you can see, I’m trying to have a user table where a user can have parent (or not).

Test code

The parent_id column is just newly added in our existing codebase. The result is that some of the test cases started failing. See example below:

FactoryGirl.create :user, parent: nil

I have already defined a factory helper for user and I just specify parent: nil above to demonstrate that it should work since my assumption is that belongs_to is optional. However, I get this error:

Parent must exist

The fix

Fortunately, the fix is easy. Just declare the belongs_to as optional which I initially assume to be the default (which seems not).

class User < ApplicationRecord
  has_many :sub_merchants, class_name: 'User', foreign_key: 'parent_id'
  belongs_to :parent, class_name: 'User', optional: true
end

That’s it!

3 thoughts on “Rails 5 – Self Join belongs_to – entity must exist error”

Leave a reply

Your email address will not be published. Required fields are marked *