Good way to handle a conditional relationship

I have a situation where each record in a table may have a relation to a record in a second table, or it may have “None.” What is a clean way to handle this kind of thing?

You could just use optional: true in your relationship declaration - ActiveRecord::Associations::ClassMethods

However, if those two types of record in the same table are two different sub-types, you could also take a look at the delegated type pattern - ActiveRecord::DelegatedType

Having been in one-sided situations at times, my heart goes out to anyone feeling trapped in a relationship with conditions. Everyone deserves to be loved for who and what they are.

(Or wait … am I in the unconditional love message board here? Cripey, this is about database things … scratch that last part …)

– composing himself properly –

uhumm … yes … it’s what @matteeyah had said – let’s say that you have Customer and Country and sometimes folks don’t supply their whereabouts … the belongs_to would look like:

class Customer < ApplicationRecord
  belongs_to :country, optional: true
1 Like