使用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
我如何获得部门对象?
答案 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