I have the following models :
class City < ActiveRecord::Base
has_many :cities_regions_relationships
has_many :regions, through: :cities_regions_relationships
end
class Region < ActiveRecord::Base
has_many :cities_regions_relationships
has_many :cities, through: :cities_regions_relationships
end
class CitiesRegionsRelationship < ActiveRecord::Base
belongs_to :city
belongs_to :region
validates :city_id, presence: true
validates :region_id, presence: true
end
What I want is to make it impossible to create a city without it linked to a region. However, before attempting that, I have to be able to create a relationship on a city that's not yet saved.
I tried this in the console (with a region already created)
c = City.new(name: "Test")
c.cities_region_relationship.build(region_id: Region.first.id)
c.save
However, this fails because the relationship doesn't have a city_id (which is normal because I didn't save the city yet, it doesn't have an ID).
I could try other ways, but I will always have the same problem : How do I create a relationship on a new object, not yet saved in database ?
If you have other completely different solutions to my initial problem (Forcing cities to have at least one region), don't hesitate to suggest something entirely different.