mardi 26 janvier 2016

Rails Converting a has_many relationship into a has and belongs to many

I have a Rails app with the following relationship:

region.rb

class Region < ActiveRecord::Base
  has_many :facilities
end

facility.rb

class Facility < ActiveRecord::Base
  belongs_to :region
end

I want to expand functionality a bit so that facilities can belong to more than one region at a time. I believe I can do this with a has_many_through relationship but I'm needing some guidance on converting the existing has_many into a has many through. I understand how to create and wire up the join table, but how would I take existing data and translate it?

So for instance. On a facility object there is region_id, since the facilities can belong to more than one region I'd probably need a region_ids field and shovel the collection of regions into that column which should then populate the other side of the association via the join table. I have this part pretty much figured out as far as moving forward and wiring up the association. But I'm unsure as to how to take existing data and translate it over so the app doesn't break when I change the model association.

Any advice would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire