Mar*_*tto 12 ruby-on-rails has-many single-table-inheritance sti ruby-on-rails-3
我一直在玩STI和belongs_to/has_many关系,我有点困惑.
基于类似于以下的模型配置,我有几个问题:
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桌面上为外键命名/添加什么?我首先想到的是添加parental_id到babies具有类似的方法沿着Baby#owner该执行以下操作:
谢谢!
在Baby属于两个Mother和Father
belongs_to :mother
belongs_to :father
您可以拥有多个外键.然后BabyDB表有两个字段,mother_id和father_id
协会的权威指南在这里:http://guides.rubyonrails.org/association_basics.html
创建Baby类的迁移看起来像这样:
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因为外键只能指向另一个记录,这意味着婴儿只有一个父母(当他们真的有两个时).
似乎,在这种情况下,你只是误解了这种关系,就是这样.你走在正确的轨道上.
| 归档时间: | 
 | 
| 查看次数: | 6884 次 | 
| 最近记录: |