Rails问题:STI的belongs_to-如何正确执行此操作? [英] Rails Question: belongs_to with STI -- how do i do this correctly?

查看:74
本文介绍了Rails问题:STI的belongs_to-如何正确执行此操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究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

  1. Baby应该属于什么?
  2. 关于迁移,我应该为外键命名/添加什么 babies表?
  3. 我很难对此进行研究,是否有明确的消息来源 这解释了这个吗? API文档似乎并没有引起人们的关注 或者我错过了(完全有可能).
  1. What should Baby belong_to?
  2. In terms of a migration, what should i name/add for foreign key on the babies table?
  3. 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属于MotherFather

belongs_to :mother
belongs_to :father

您可以有多个外键.然后,Baby DB表具有两个字段,mother_idfather_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.motherbaby.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屋!

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