Rails的ActiveRecord模型链表 [英] Rails ActiveRecord Model Linked List

查看:158
本文介绍了Rails的ActiveRecord模型链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在密集的谷歌搜索我现在就说明了这似乎不经常发生的问题,但仍然是非常基本的。在活动记录链表。至于我现在,我们需要在模型两会:

after intensive googling I will now state out a problem which seems to not occur often, but still is very basic. Linked Lists in Active Record. As far as I am now, we need two associations in the model:

class Child < ActiveRecord::Base
  belongs_to :parent
  belongs_to :next, :class_name => 'Child', :foreign_key => 'next_id'
  belongs_to :previous, :class_name => 'Child', :foreign_key => 'previous_id'
end

所以,现在我们可以得到父母的所有子:

So now we can get all children of a parent:

children = Child.where("parent_id = ?", parent_id)

和现在的问题是:我当然要来从一个查询数据库中的所有孩子,但我也想通过在链接顺序,孩子这意味着第一个将成为孩子的$ P零的$ pvious属性,下一子将其由下一个属性的首创连接在所述一方,依此类推,直到下一个属性是零。 是否有可能像这样做,或做我需要查询的第一个孩子,然后再去儿童之间没有precaching?

And now to the question: I want of course to get all children from the database with one query, but I also want to go through the children in the linked order, which means first one will be the child with the previous attribute of nil, the next child will be the one which is connected by the firsts next attribute, and so on until the next attribute is nil. Is it possible to do it like this, or do I need to query the first child, and then go from child to child without "precaching"?

推荐答案

度假排名模型的宝石有其他的替代品。 第一个使用类似链表的方法。第二个使用位置属性。

The resort and ranked-model gems are other alternatives. The first one uses an approach similar to linked lists. The second one uses a position attribute.

这篇关于Rails的ActiveRecord模型链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆