0

2つのモデルの両方が外部ID => tweeter_idを設定する理由がわかりません

私の考えでは、外部キーは1つのモデルの主キーを指すことです

たとえば、モデルAとBがあります

モデル B はモデル A を参照したいと考えています。

しかし、モデル A のデフォルトの主キーは、a_id ではなく aaa_id に変更された可能性があります。

モデル B は、モデル A を参照するために外部キーとして aaa_id を設定する必要がありますか?

モデル Tweet に外部キーを追加する必要がある理由がわかりません。

そして、モデル 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
4

2 に答える 2

0

と は同じ関係の両面であるhas_oneと考えてください。belong_to

Locationを参照しますTweet-- 外部キーを持っていますtweeter_id.

一方Tweet、 は場所を参照しません。. はありませんlocation_id

したがって、ここには 1 つの関係がありますTweet <-> Location。外部キーは 1 つだけです。外部キーは、あるテーブルのキーであり、別のテーブルのキーへの参照であることを思い出してください。

thehas_oneと the belong_toassociation の両方が、この 1 つの関係を参照し、その異なる側に存在するだけです。どちらもこの場所を参照するため、どちらも をtweeter_id外部キーとして使用します。

于 2013-11-03T05:26:44.757 に答える