Rails Question: belongs_to with STI — how do i do this correctly?

自作多情 提交于 2019-12-05 00:07:41

The Baby belongs to both Mother and Father

belongs_to :mother
belongs_to :father

You can have multiple foreign keys. The Baby DB table then has two fields, mother_id and father_id

The definitive guide to associations is here: http://guides.rubyonrails.org/association_basics.html

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

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.

I've solved a similar problem myself by adding an explicit foreign_key call.

Something like the following code:

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 :mother, foreign_key: 'parental_id'
    belongs_to :father, foreign_key: 'parental_id'
end

Of course, this assumes that a baby has only one parent. :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!