Rails - 父/子关系
我目前正在使用标准的一对一关系来处理父/子关系:
class Category < ActiveRecord::Base
has_one :category
belongs_to :category
end
是否有推荐的方法来做到这一点,或者这样可以吗?
I'm currently using a standard one-to-one relationship to handle parent/child relationships:
class Category < ActiveRecord::Base
has_one :category
belongs_to :category
end
Is there a recommended way to do it or is this ok?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要调整您使用的名称才能使其正常工作 - 您指定关系的名称,然后告诉 AR 该类是什么:
You will need to tweak the names you are using to get this working - you specify the name of the relationship, and then tell AR what the class is:
我发现我必须对 @equivalent8 的解决方案进行一些小的更改,以使其适用于 Rails 5 (5.1.4):
如果没有
foreign_key
声明,Rails 会尝试通过 Organization_id 而不是 Parent_id 查找子项和窒息。如果没有
:optional => ,Rails 也会卡住。 true
声明了 own_to 关联,因为在 Rails 5 中,belongs_to 要求默认分配一个实例。在这种情况下,您必须分配无限数量的父级。I found that I had to make a minor change to @equivalent8's solution to make it work for Rails 5 (5.1.4):
Without the
foreign_key
declaration, Rails tries to find the children by organization_id instead of parent_id and chokes.Rails also chokes without the
:optional => true
declaration on the belongs_to association since belongs_to requires an instance to be assigned by default in Rails 5. In this case, you would have to assign an infinite number of parents.有_许多版本:
has_many version:
我想,应该是foreign_key
控制台:
I think , should be foreign_key
Console :
如果您已经有一个模型
类别
和一个表类别
(在schema.rb中),您可以这样做模型:这作为迁移:
注意:在较新版本的 Ruby 中,您不需要火箭哈希
=>
If you already have a model
Category
and a tablecategories
(in schema.rb) you could do this to the model:and this as a migration:
NOTE: In newer versions of Ruby you don't need the rocket hashes
=>
由于这种关系是对称的,我实际上发现与托比所写的不同,我更喜欢以下内容:
出于某种原因“有一个父母,许多孩子”是我的想法,而不是“有许多父母,只有一个孩子”
Since the relation is symmetric, I actually find that different than what Toby wrote, that I prefer the following:
For some reason "has one parent, many children" is the way my mind things, not "has many parents, only one child"