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

时间:2016-11-18 07:29:13

标签: ruby-on-rails ruby ruby-on-rails-3 mongoid

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

我如何获得部门对象?

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

使用的方法环绕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
相关问题