3

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.

alopez02
  • 1,524
  • 2
  • 17
  • 36

2 Answers2

2

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
Igor Drozdov
  • 14,690
  • 5
  • 37
  • 53
1

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

If you are using Rails 5, you can add optional: true to tell Rails not to validate the presence of referee_id

From the Guides

If you set the :optional option to true, then the presence of the associated object won't be validated. By default, this option is set to false.

  belongs_to :referee, class_name: "Waiter", optional: true
Pavan
  • 33,316
  • 7
  • 50
  • 76