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
There are a couple things wrong with this.
You need to specify a belongs_to
on the other side of a has_many
or has_one
association. The model that defines a belongs_to
association is where the foreign key belongs.
So if an Organization has_one :city
, then a City needs to belongs_to :organization
. Alternatively, if a City has_one :organization
, then the Organization needs to belongs_to :city
.
Looking at your setup, it looks like you want the belongs_to
definition inside the City
model.
The migrations aren't built off the model definitions. Instead, they are built from the db/migrations
folder. A migration is created when you run the rails g model
command (or rails g migration
). In order to get a foreign key, you need to tell the generator to create it.
rails generate model organization name:string description:string url:string city_id:integer
Or
rails generate model city name:string description:string url:string organization_id:integer