我就是不明白为什么这两个模型都设置了外国 id => tweeter_id
在我看来,外键是指向一个模型的主键
例如有模型A和B
模型 B 想引用模型 A。
但是模型 A 的默认主键可能已经更改为 aaa_id 而不是 a_id 了。
所以模型 B 必须将 aaa_id 设置为外键才能引用模型 A?
我不明白为什么我们应该在模型推文上添加外键,
并且模型 Tweet 没有 tweeter_id 列。
问题描述
FOREIGN KEY
Objective
OH NO! Our Database Admin turned into a Zombie and decided to rename the belongs_to
field in our locations table tweeter_id instead of the intelligent default tweet_id.
We're going to slay him and correct this, but in the meantime set the foreign_key on
both relationships to tweeter_id.
Also set the dependency so when a tweet is destroyed,
the location is destroyed as well.
=结束
模型文件
class Tweet < ActiveRecord::Base
has_one :location ,dependent: :destroy, foreign_key: :tweeter_id
end
class Location < ActiveRecord::Base
belongs_to :tweet, class_name: "Tweet" , foreign_key: :tweeter_id
end
方案
ActiveRecord::Schema.define(:version => 20110814152905) do
create_table "locations" do |t|
t.integer "name"
t.integer "tweeter_id" # BRAINS!!!
end
create_table "tweets" do |t|
t.string "message"
t.boolean "show_location", :default => false
t.integer "zombie_id"
t.timestamps
end
end