Active Record树模型

时间:2016-03-07 14:49:04

标签: ruby-on-rails postgresql activerecord ancestry

我已经搜索了很长时间,但无法找到有关我想要实现的信息。

我正在努力实现像祖父 - 父亲 - 孩子tree这样的事情。我已经使用祖先宝石设置我的模型/迁移,并且它按预期工作。我可以通过在模型上调用subtree来创建子项并查看整个子树。

我有一个单独的表,例如消息。我希望能够看到所有留言 2-2 及其后代(2-2-1,2-2-2,2-2-2-1,2-2-2) -2)。同样,在检查 2-2-2-2 的消息时,我只希望显示这些消息,因为它没有子树/子节点。

我还需要仅在给定的根id(例如1或2)内操作。

我已尝试以下方法来实现这一目标:

迁移

create_table :customers do |t|
  t.string :name, null: false
end

create_table :messages do |t|
  t.belongs_to :customer, index: true

  t.datetime :created_at
  t.string :message, null: false
end

add_column :customers, :ancestry, :string
add_index :customers, :ancestry

模型

class Customer < ActiveRecord::Base
  has_ancestry
  has_many :messages, dependent: :destroy
end

class Message < ActiveRecord::Base
  belongs_to :customer
end

当前实施

subtree_ids = Customer.find(customer_id).subtree.find(sub_customer).subtree_ids
Message.where(customer_id: subtree_ids)

这是有效的,但它执行4个查询,因为它需要找到客户ID,在其子树中查找子帐户,检索可用的子树ID,然后将它们传递给消息以在该客户ID数组内搜索。

我可以将其归结为2个查询,一个用于获取给定sub_customer的subtree_ids,然后将它们传递给消息。但是,我需要确保它在给定的customer_id内运行。

非常感谢有关如何实现或优化的任何帮助/伪代码,我对AR / SQL来说还是一个新手。

0 个答案:

没有答案
相关问题