Active Record with Delegate and conditions

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

Answers


No, you can't, but you can pass the :allow_nil => true option 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 need to write your own custom method instead using the delegate macro for more complex options.

class User < ActiveRecord::Base
  # ...

  def company
    master.company if has_master?
  end

end

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

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

Need Your Help

What is deserialize and serialize in JSON?

json serialization deserialization json-deserialization json-serialization

I'm new in JSON. Now, I need to use JSON for my Flash ActionScript 3.0. So I found one lib for JSON, and I have seen the terms "deserialize" and "serialize". What do they mean?

disable autorotate on a single UIViewController in iOS6

objective-c xcode ios6 uiinterfaceorientation autorotate

I have a project using UINavigationController and segues working properly good, all of them rotate correctly, the thing is... I just want to disable autorotation on a specific UIViewController.