I am wondering how to do the association in Rails correct. First I create a City model and an Organisation. Now I want to have an Organisation have a City... this is done by adding the has_many
and has_one
associations. After that I run rake db:migrate
. But somehow it does not create a field city
or city_id
in my database model. Do I have to do this myself? Shouldn't rails now create a foreign key constraint in the database?
To see if it has worked I am using rails c
and type in Organisation
the answer is the following:
=> Organisation(id: integer, name: string, description: string, url: string, created_at: datetime, updated_at: datetime)
Please excuse my stupid question... I am a beginner in Rails and everything is still very unfamiliar.
Thanks!
City:
class City < ActiveRecord::Base
has_many :organisations
end
Organisation:
class Organisation < ActiveRecord::Base
has_one :city
end
Create City:
class CreateCities < ActiveRecord::Migration
def change
create_table :cities do |t|
t.string :name
t.string :country
t.timestamps
end
end
end
Create Organisation:
class CreateOrganisations < ActiveRecord::Migration
def change
create_table :organisations do |t|
t.string :name
t.string :description
t.string :url
t.timestamps
end
end
end