[ACCEPTED]-Active Record with Delegate and conditions-delegates

Accepted answer
Score: 42

No, you can't, but you can pass the :allow_nil => true option 4 to return nil if the master is nil.

class User < ActiveRecord::Base
  delegate :company, :to => :master, :allow_nil => true

  # ...
end

user.master = nil
user.company 
# => nil

user.master = <#User ...>
user.company 
# => ...

Otherwise, you 3 need to write your own custom method instead 2 using the delegate macro for more complex 1 options.

class User < ActiveRecord::Base
  # ...

  def company
    master.company if has_master?
  end

end
Score: 2

I needed to delegate the same method to 2 two models, preferring to use one model 1 over the other. I used the :prefix option:

from individual.rb

delegate :referral_key, :email, :username, :first_name, :last_name, :gender, :approves_email, :approves_timeline, to: :user, allow_nil: true, prefix: true                                
delegate :email, :first_name, :last_name, to: :visitor, allow_nil: true, prefix: true

def first_name
  user.present? ? user_first_name : visitor_first_name
end

More Related questions