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_toon the other side of ahas_manyorhas_oneassociation. The model that defines abelongs_toassociation is where the foreign key belongs.So if an Organization
has_one :city, then a City needs tobelongs_to :organization. Alternatively, if a Cityhas_one :organization, then the Organization needs tobelongs_to :city.Looking at your setup, it looks like you want the
belongs_todefinition inside theCitymodel.The migrations aren’t built off the model definitions. Instead, they are built from the
db/migrationsfolder. A migration is created when you run therails g modelcommand (orrails g migration). In order to get a foreign key, you need to tell the generator to create it.Or