Rails 4 - 如何动态引用与自身相关的未知 table?
Rails 4 - How to dynamically reference an unknown table related to itself?
在尝试为动态生成的索引视图构建一个自动过滤系统时,我发现需要在同一个 table 上处理相关记录(例如,一个任务通过一个任务属于任务parent_id 字段设置为外键。如何引用关联的自身 table?
下面的 'klasses' 示例是有问题的插图。
# Compile recursive array based on parent_id,
# where parent_id is foreign_key on it's same table
def build_recursive(conditions)
@children = []
klass = current_controller.singularize.constantize.where(conditions).all
def fetch_subs(sub)
sub.klasses.where(conditions).order(:sort).each do |child| <-- how to dynamically reference 'klasses'?
@children << child
fetch_subs(child)
end
return @children
end
klass.klasses.each do |record| <-- how to dynamically reference 'klasses'?
@children << record
fetch_subs(record)
end
return @children
end
在此示例中,如何动态引用 'klasses',其中类是当前控制器的相关且相同的 table?
此外,如果有现有的 gem 或更好的解决方案,我将不胜感激地接受其他建议。提前致谢。
看看 ancetry gem 它会让你轻松管理 parent->children 关系。
在尝试为动态生成的索引视图构建一个自动过滤系统时,我发现需要在同一个 table 上处理相关记录(例如,一个任务通过一个任务属于任务parent_id 字段设置为外键。如何引用关联的自身 table?
下面的 'klasses' 示例是有问题的插图。
# Compile recursive array based on parent_id,
# where parent_id is foreign_key on it's same table
def build_recursive(conditions)
@children = []
klass = current_controller.singularize.constantize.where(conditions).all
def fetch_subs(sub)
sub.klasses.where(conditions).order(:sort).each do |child| <-- how to dynamically reference 'klasses'?
@children << child
fetch_subs(child)
end
return @children
end
klass.klasses.each do |record| <-- how to dynamically reference 'klasses'?
@children << record
fetch_subs(record)
end
return @children
end
在此示例中,如何动态引用 'klasses',其中类是当前控制器的相关且相同的 table?
此外,如果有现有的 gem 或更好的解决方案,我将不胜感激地接受其他建议。提前致谢。
看看 ancetry gem 它会让你轻松管理 parent->children 关系。