我正在尝试编写一个可以产生反向外键查找的方法。我们的想法是,给定单个Rails模型类,我可以反映获取所有ActiveRecord反射并提取父表名和外键。
这对于简单的has和has_many关系来说是微不足道的,即使是多态也是如此。我遇到的困难是处理关系。我不确定我是否需要将belongs_to作为用例处理。
这是我到目前为止的代码
def add_association(klass_name, association)
associated_model = association.class_name
@association_hash[klass_name][associated_model] ||= {}
if association.is_a? ActiveRecord::Reflection::ThroughReflection
add_through_reflection(klass_name, associated_model, association)
elsif association.is_a? ActiveRecord::Reflection::AssociationReflection
add_association_reflection(klass_name, associated_model, association)
else
raise "Unhandled ActiveRecord::Reflection association type"
end
end
def add_association_reflection(klass_name, associated_model, association)
return if association.macro == :belongs_to
begin
@association_hash[klass_name][associated_model][:macro] = association.macro
@association_hash[klass_name][associated_model][:assocation_class] = association.class
@association_hash[klass_name][associated_model][:assocation] = association
@association_hash[klass_name][associated_model][:table_name] = association.klass.table_name
@association_hash[klass_name][associated_model][:pk] = association.klass.primary_key
@association_hash[klass_name][associated_model][:fk] = association.foreign_key
@association_hash[klass_name][associated_model][:type] = klass_name if association.foreign_key != klass_name.underscore + "_id"
rescue StandardError => e
store_the_error(associated_model, e)
end
end
add_through_reflection
方法现在正在检索宏,association_class和关联。我通过ThroughReflection
方法同时运行AssociationReflection
和add_association_reflection
,但ThroughReflection
类型的pks和fks不正确。