如果我们在当前模型中有相同的方法名称,如何调用活动记录的关联方法

How to call active record's association method if we have same method name in current model

使用 Ruby 和 Rails,我做了以下代码

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

这里来自 department method 我需要 department object

如果我执行以下代码,则可以根据 rails 关联轻松获得部门对象

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

如何获取部门对象?

您可以使用关联方法,然后加载关联的目标,例如:

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

这将加载相关关联,而不是递归调用您的部门方法

使用了 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

未在控制台测试,但理论上,我认为 super 应该足够了:

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 将尝试在 Parent class

的 superclass 中找到#department 方法

更多信息在这里:https://medium.com/rubycademy/the-super-keyword-a75b67f46f05