【问题标题】:Rails Thinking Sphinx Indexing Self Join Associations Tree StructureRails Thinking Sphinx Indexing Self Join Associations 树结构
【发布时间】:2012-08-08 03:02:34
【问题描述】:

我有属于某个类别的产品。类别构成一棵树 通过让父母和孩子使用自联接来构建结构:

协会:

class Category < ActiveRecord::Base
  has_many :children, class_name: "Category", foreign_key: "parent_id"
  belongs_to :parent, class_name: "Category"
end

class Product < ActiveRecord::Base
  belongs_to :category
end

例如,

Fruits & Vegetables     =>    "High" Category 
Fresh Fruits            =>    "Intermediate" Category
Citrus                  =>    "Low" Category
Limes Large             =>    Product

我想使用 Thinking Sphinx 来索引“低”类别名称和 产品的“高”类别名称,甚至可能是树层次结构中介于两者之间的所有类别名称。

索引低类别父名称没有问题,如下所示:

class Product < ActiveRecord::Base
  indexes :name
  indexes category.parent.name, as: :low_category
end

注意:“高”和“低”类别之间的节点数是可变的。我需要一种动态添加分层名称的方法。

但是如何在树中进一步索引类别名称?我知道我不能使用方法 在 TS 索引中,我该如何设置数据库?

最重要的是,如何索引“高”类别名称?

【问题讨论】:

    标签: ruby-on-rails tree indexing associations thinking-sphinx


    【解决方案1】:

    你能做到吗?

    class Product < ActiveRecord::Base
      indexes :name
    
      category = category.parent
      indexes category.name, as: :low_category
    
      while category.parent do
        if category.parent
          indexes category.name, as: :root_category
        elsif category.parent
          indexes category.name, as: :high_category
        else
          indexes category.name
        end
    
        category = category.parent
      end
    end
    

    【讨论】:

    • 是的,这适用于特定情况,但高和低类别之间的节点数量是可变的。我需要动态生成这些并将高类别名称与所有其他名称分开。在 TS 中有什么方法可以做到这一点?
    • 我改变了答案。这可能不是更好的解决方案,但它应该可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多