我正在创建一个gem来导出一小部分相关的ActiveRecord对象。有没有更好的方法来查找ActiveRecord对象的孩子和父母?
以下是我目前如何找到父母&孩子。
# belongs_to, based on column names with an _id suffix
def belongs_to_relations(ar_instance)
columns = ar_instance.class.column_names
parents = columns.map{ |c| c if c =~ /_id/ }.reject{ |c| c.nil? }
parents.map!{ |parents| parents.gsub('_id', '') }
end
# has_many, based on existence of a xxx_id column in other tables
def has_many_relations(ar_instance)
column_name = "#{ar_instance.class.name.underscore}_id"
descendents = ActiveRecord::Base.connection.tables
descendents.reject!{ |table| false unless table.classify.constantize rescue true }
descendents.reject!{ |table| true unless table.classify.constantize.column_names.include?(column_name) }
end
有没有更好的方法来找到这些关系?这工作好,但遥远的关系,如:通过,我必须手动指定。