Rails问题:STI的belongs_to-如何正确执行此操作? [英] Rails Question: belongs_to with STI -- how do i do this correctly?
问题描述
我一直在研究STI和belongs_to/has_many关系,我有点困惑.
I've been playing around with STI and belongs_to / has_many relationships and I'm a bit confused.
基于与以下类似的模型配置,我有几个问题:
I have a few questions based on a model configuration similar to:
class Parental < ActiveRecord::Base
end
class Mother < Parental
has_many :babies
end
class Father < Parental
has_many :babies
end
class Baby < ActiveRecord::Base
belongs_to :??????
end
-
Baby
应该属于什么? - 关于迁移,我应该为外键命名/添加什么
babies
表? - 我很难对此进行研究,是否有明确的消息来源 这解释了这个吗? API文档似乎并没有引起人们的关注 或者我错过了(完全有可能).
- What should
Baby
belong_to? - In terms of a migration, what should i name/add for foreign key on
the
babies
table? - I've had a hard time researching this, is there a definitive source that explains this? The API docs did not seem to hit it on the head OR i missed it (which is totally possible).
我首先想到的是将parental_id
添加到babies
以及类似Baby#owner
的方法,该方法执行以下操作:
My first thought is add parental_id
to babies
along with a method like Baby#owner
that does the following:
- 拥有self.parental
- 确定父母的类型
- 返回正确的父母类型(可以是母亲,可以是父亲)
谢谢!
推荐答案
Baby
属于Mother
和Father
belongs_to :mother
belongs_to :father
您可以有多个外键.然后,Baby
DB表具有两个字段,mother_id
和father_id
You can have multiple foreign keys. The Baby
DB table then has two fields, mother_id
and father_id
此处是协会的权威指南: http://guides.rubyonrails.org/association_basics.html
The definitive guide to associations is here: http://guides.rubyonrails.org/association_basics.html
创建Baby
类的迁移看起来像这样:
The migration to create the Baby
class would look something like this:
class CreateBabies < ActiveRecord::Migration
def self.up
create_table :babies do |t|
t.integer :father_id
t.integer :mother_id
end
end
def self.down
drop_table :babies
end
end
这给您类似的东西:
baby.mother
和baby.father
.您不能只有一个parental_id
,因为外键只能指向另一条记录,这意味着婴儿只有一个父母(实际上他们只有两个父母).
This gives you things like:
baby.mother
and baby.father
. You can't have a single parental_id
because the foreign key can only point to one other record, meaning that babies would only have one parent (when really they have two).
似乎,在这种情况下,您只是误解了这种关系而已.您在正确的轨道上.
Seems like, in this case, you're just misunderstanding the relationship, is all. You are on the right track.
这篇关于Rails问题:STI的belongs_to-如何正确执行此操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!