0

Using Ruby and Rails, I did following code

class Department
end
class Employee
  field :depaertment_id, :default => nil
  belongs_to :department, :autosave => false
  def department
    dept = self.super.department # check whether associated department object exists as per self.department active record's method
    if dept.nil?
      #other operation
    end
  end
end

Here from department method I need get department object

If I do following code then department object is easily available as per rails association

class Employee
 field :depaertment_id, :default => nil
 belongs_to :department, :autosave => false
 def get_department
   dept = self.department 
   if dept.nil?
     #other operation
   end
 end
end

How can I get department object?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Darshan Patel
  • 3,176
  • 6
  • 26
  • 49

3 Answers3

1

You could use the association method and then load the target of the association, for example:

def department
    dept = self.association(:department).load_target
    if dept.nil?
        #other operation
    end
end

this will load the related association instead of recursively calling your department method

John Hayes-Reed
  • 1,358
  • 7
  • 13
0

Used Method Wrapping from Monkey patching

class Department
end
class Employee
  field :depaertment_id, :default => nil
  belongs_to :department, :autosave => false
  old_dept = instance_method(:department)
  define_method(:department) do
  dept = old_bar.bind(self).()
  if dept.nil?
      #other code...
  end
end
Community
  • 1
  • 1
Darshan Patel
  • 3,176
  • 6
  • 26
  • 49
0

Not tested in console, but in theory, I think super should be enough:

class Employee
  belongs_to :department, :autosave => false

  def department
    # super will load the department association

    if super.nil?
      # Do your override here.
    else
      # to return the default
      super
    end
  end
end

super will try to find #department method in the superclass of the Parent class

More info here: https://medium.com/rubycademy/the-super-keyword-a75b67f46f05