newBike
newBike

Reputation: 15002

Foreign key in two models on Rails 3 from code school sample

I just can not why the two model both set the foreign id => tweeter_id

In my thought, the foreign key is to point to one model's primary key

For example there are model A and B

the model B wants to refer to model A.

But the default primary key of model A maybe has changed to aaa_id not being a_id anymore.

So the model B has to set aaa_id as it's foreign key in order to refer to model A?

I can't understand why we should add foreign key on model Tweet,

And the model Tweet doesn't have the column tweeter_id.

The question's description

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.

=end

The model file

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

The scheme

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

Upvotes: 0

Views: 177

Answers (2)

Brian Mendez
Brian Mendez

Reputation: 27

Remember, the belongs_to :tweet in class Location has already been defined prior. Since it has been changed, you must create a new reference to link the two.

class Tweet < ActiveRecord::Base
  has_one :location, foreign_key: :tweeter_id, dependent: :destroy
end

class Location < ActiveRecord::Base
  belongs_to :tweet, foreign_key: :tweeter_id  
end

Upvotes: 1

micahbf
micahbf

Reputation: 627

Think of has_one and belong_to being two sides of the same relation.

The Location refers to the Tweet -- it has the foreign key, tweeter_id.

The Tweet on the other hand, does not refer to the location -- it doesn't have a location_id.

So, there is one relation here: Tweet <-> Location. There is only one foreign key -- remember that a foreign key is a key in one table that is a reference to a key in another table.

Both the has_one and the belong_to associations refer to this one relation, just existing on different sides of it. Since they both refer to this location, they both use the tweeter_id as the foreign key.

Upvotes: 0

Related Questions