Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a self join association be done allowing the reference to be blank?

My app has a Waiter model to manage a list of people who are on a waiting list. Each of those 'waiters' can refer others so they can join the list. Also, I want to track down who's referred a particular waiter.

I have defined a self join association so that each waiter can be referenced to a referee so I've done the following in my model:

#models/waiter.rb
class Waiter < ApplicationRecord
  has_many :referrals, class_name: "Waiter",
                            foreign_key: "referee_id"
  belongs_to :referee, class_name: "Waiter"
end

Plus migrated the following migration:

class AddRefereeReferenceToWaiters < ActiveRecord::Migration[5.1]
  def change
    add_reference :waiters, :referee, index: true
  end
end

This seems to be a logical solution, however, some 'waiters' may not be referred by anyone, in which case I'd like to leave referee_id in the Waiters table blank. The same happens with the first waiter of all (who won't be referred by anyone.

So, when trying to save any new waiter to the db I'm facing a rollback with the error :referee=>["must exist"].

Is it possible then to instruct rails to not validate the presence of a reference id?

I've tried adding a referee_id of zero in the controller when it's empty but this gets rolled back as well.

like image 264
alopez02 Avatar asked Dec 04 '25 08:12

alopez02


1 Answers

Since Rails 5 when you define belongs_to association it's required by default

To make referee optional you need to provide optional: true option:

class Waiter < ApplicationRecord
  has_many :referrals, class_name: "Waiter",
                        foreign_key: "referee_id"
  belongs_to :referee, class_name: "Waiter", optional: true
end
like image 56
Igor Drozdov Avatar answered Dec 06 '25 00:12

Igor Drozdov