0

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.

Kaidjin
  • 1,433
  • 1
  • 12
  • 18
  • Can a `city` have multiple `regions`? – AbM Dec 16 '13 at 22:12
  • @AbM Yes. Otherwise I could have used has_many and belongs_to, but unfortunately my model is not that simple :( – Kaidjin Dec 16 '13 at 22:16
  • Check this [SO post](http://stackoverflow.com/questions/950008/validate-at-least-one-in-has-and-belongs-to-many) – AbM Dec 16 '13 at 22:24

1 Answers1

0

You do not need to build a cities_region_relationship. By passing region_ids to a new City instance, this will create the cities_region_relationship for you.

You can try in the console:

c = City.new(name: "Test", region_ids: [an array of existing region ids])
c.save

for the validation, you can define a new validate method that checks if self.regions.blank? like mentioned in the SO post in my comment above.

AbM
  • 7,326
  • 2
  • 25
  • 28
  • This does not work unfortunately : `c.errors` gives me `#, @messages={:cities_regions_relationships=>["is invalid"]}>`. As you can see the relationship as no city_id and is invalid. – Kaidjin Dec 17 '13 at 07:05
  • I forgot to mention to remove the validations in `CitiesRegionsRelationship` i.e. you do not need `validates :city_id, presence: true` or `validates :region_id, presence: true`. Your validation is only happening in the `City` model to check if an instance has an array of `regions` that is not `blank` – AbM Dec 17 '13 at 14:53