我有一组对象,其中一些具有organization_id属性,另一些对象委托organization_id。
例如:
class Department
belongs_to :organization
end
class Program
belongs_to :department
delegate :organization_id, to: :department
end
class Role
belongs_to :organization
end
class UsersRole
belongs_to :role
delegate :organization_id, to: :role
end
我想用一种方法以编程方式确定将organization_id委派给哪个对象类,以便我可以执行以下操作
def find_organization_id_source(object)
object.organization_id.method_im_hoping_exists
end
$ find_organization_id_source(@program)
>> Department
$ find_organization_id_source(@users_role)
>> Role
答案 0 :(得分:4)
这是不可能的。从active_support/core_ext/module/delegation.rb
的源代码中可以看出,Rails创建了一个内部调用委托方法的新方法。
答案 1 :(得分:0)
def is_delegated?(object, delegated_attribute)
object.attributes.include? delegated_attribute
end
它不会告诉你从哪里获得价值,但它应该告诉你你是否通过授权获得了它。