1

I have 2 important entities and an association table that is created with foreign keys

class Assoc << ActiveRecord::Base
    belongs_to entity1
    belongs_to entity2
end

class Entity1 << ActiveRecord::Base
    has_many :assocs
    has_many :entities2 :through=>:assocs
end

class Entity2 << ActiveRecord::Base
    has_many :assocs
    has_many :entities1 :through=>:assocs
end

I saw this question how to add records to has_many :through association in rails and it seems reasonable to me, except for the fact that it seems that he can create an instance of Assoc without having Entity1 and Entity2 assigned for it. This doesn't seem to be my case.

In my specific case I am dealing with Properties and Property Facilities. The assoc table will only link a property with many property facilities and vice versa. Assoc is defined by 2 fks, one for each entity.

Once I submited a form, I'm in the action now. I already got the Property and stored it in @property. Now I want to add the facilities that are in params[:property][:facility_ids] (its an array of ids).

What should I do?

Community
  • 1
  • 1
Victor Ferreira
  • 6,151
  • 13
  • 64
  • 120

2 Answers2

0

You can accomplish deletion with a dependent: destroy

class Entity1 < ActiveRecord::Base
  has_many :assocs
  has_many :entities2, through::assocs, dependent: :destroy
end

As for insert, you can do something like:

facility_ids = params[:property][:facility_ids]
facility_array = []

facility_ids.each do |id|
  facility_array << facility.find(id)
end

@property.facilities = facility_array
Chase
  • 2,748
  • 2
  • 23
  • 32
  • alright, so I HAVE to do this with loops? I got a question regarding the deletion. what if I want to delete only ONE facility in that property? the facility will remain on the system, but the property won't have it anymore (imagine that I unchecked the checkbox, for example) – Victor Ferreira Aug 13 '15 at 15:09
  • I was looking for something like `Property.last.property_facilities.some_method_to_assign(facility_id: Facility.find(params[:facility_ids]))` – Victor Ferreira Aug 13 '15 at 15:16
  • 1
    and I get this error with your code PropertyFacility(#-648607518) expected, got Facility(#-651473278) – Victor Ferreira Aug 13 '15 at 15:39
  • ahh an object id problem... You could create an array of facilities first, then add that whole array to @property. And yeah, if there was `some_method_to_assign` it would just be a loop of find and assign under the hood, fwiw. – Chase Aug 13 '15 at 15:54
0

You can use

@property.update_attributes property_facility_ids: (@property.property_facility_ids << params[:property][:facility_ids])

to append PropertyFacility associations, assuming your model Property has_many :property_facilities :through=>:assocs.

The above simply pushes PropertyFacility from params onto @property, you can do additional validations as necessary.

Fan Jin
  • 400
  • 5
  • 12