与自身具有一对一关系的模型

与自身具有一对一关系的模型

本文介绍了Rails 3 - 与自身具有一对一关系的模型 - 我是否需要belongs_to的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Person 的模型.它有两个属性 - name 和 parent_person_id

I have a model named Person. It has two properties - name and parent_person_id

一个人总会有一个父人.

A person will always have a parent person.

我应该在模型中使用belongs_to吗?如果是这样,这样做有什么好处.

Should I be using belongs_to in the model? If so, what are the advantages of doing so.

class Person < ActiveRecord::Base
    belongs_to :person
end

我还没有试过这段代码,我的正常 mysql 方式似乎有点错误.

I've not tried this code out yet, it seems a bit wrong my normal mysql ways.

我在这里寻找意见比什么都重要,我对 Rails 还很陌生,想确保我做的事情正确,做事按照 Rails 的方式".

I'm looking for opinions here more than anything, I'm quite new to the rails and want to make sure I'm doing things properly, doing things 'the Rails way'.

推荐答案

我建议使用像 ancestry 对于这样的树结构.它为您提供关联以及许多实用方法(查找父、子、兄弟姐妹、检索子树).

I'd suggest using a gem like ancestry for a tree structure like that. It gives you your association plus lots of utility methods (finding parent, children, siblings, retrieving a subtree).

如果您不想要那样,那么在您的belongs_to 关联中必须如下所示:

If you don't want that, then in your belongs_to association has to look like this:

belongs_to :person, :foreign_key => "parent_person_id"

因为没有这个选项,rails 会寻找一个 person_id 的外键,如果没有找到, 抛出一个错误消息.

since without that option, rails would look for a foreign key of person_id and, not finding that, throw an error message.

这篇关于Rails 3 - 与自身具有一对一关系的模型 - 我是否需要belongs_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!