I'm starting with Ruby on Rails and I have these two models:
City and Street,
These two models were generated independently with no relation between them. Now I need a city to have many streets and each street to belong to a single city. I ran this command:
bin/rails generate migration AddCityRefToStreets city:references
That generated this migration:
class AddCityRefToStreets < ActiveRecord::Migration[5.2]
def change
add_reference :streets, :city, foreign_key: true
end
end
Then I ran bin/rails db:migrate
and then I went into these model classes and wrote:
class City < ApplicationRecord
has_many :streets, dependant: :destroy
end
and
class Street < ApplicationRecord
belongs_to :city
end
Rails did not show any complains, and so far it works fine for me. If I ask @city.streets.length
it will return the correct amount of streets for that @city
. If I ask @street.city
it returns the correct city as well.
The thing is, I went into the database using DBeaver and the migration did not generate relations between the cities
and streets
tables. The streets
table shows me a city_id
field, but still not showing any relationship in the ER Diagram view.
My question is: what am I missing here? Is this the correct way to relate two entities created independently?
I'm using Linux Mint 18.3, Rails 5.2.1, Sqlite 3.11.0 and DBeaver 5.1.
The add_reference
migration command will have added a city_id
column to your streets
table.
When you call @city.streets
, it is evaluated as the equivalent of Street.where(city_id: @city.id)
.
Similarly, @street.city
will look at the ID stored in city_id
column, and do a lookup - the equivalent of City.find(@street.city_id)
.