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.