Is it possible to use delegate in your Active Record model and use conditions like :if
on it?
class User < ApplicationRecord
delegate :company, :to => :master, :if => :has_master?
belongs_to :master, :class_name => "User"
def has_master?
master.present?
end
end
No, you can't, but you can pass the
:allow_nil => true
option to return nil if the master is nil.Otherwise, you need to write your own custom method instead using the delegate macro for more complex options.
I needed to delegate the same method to two models, preferring to use one model over the other. I used the :prefix option:
from individual.rb