使用has_many插入和删除记录:通过关联,其中关联取决于两个fks

时间:2015-08-13 14:46:48

标签: ruby-on-rails ruby-on-rails-4 activerecord associations has-many-through

我有两个重要的实体和一个用外键创建的关联表

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

我看到了这个问题how to add records to has_many :through association in rails,这对我来说似乎是合理的,除了它似乎可以创建一个Assoc的实例,而没有为它分配Entity1和Entity2。这似乎不是我的情况。

在我的具体案例中,我正在处理物业和物业设施。关联表仅链接具有许多属性设施的属性,反之亦然。 Assoc由2个fks定义,每个实体一个。

一旦我提交了一份表格,我现在正在采取行动。我已经获得Property并将其存储在@property中。现在我想添加params[:property][:facility_ids](它的一组id)中的设施。

我该怎么办?

2 个答案:

答案 0 :(得分:0)

您可以使用dependent: destroy

完成删除
class Entity1 < ActiveRecord::Base
  has_many :assocs
  has_many :entities2, through::assocs, dependent: :destroy
end

至于插入,您可以执行以下操作:

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

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

@property.facilities = facility_array

答案 1 :(得分:0)

您可以使用

@property.update_attributes property_facility_ids: (@property.property_facility_ids << params[:property][:facility_ids])
假设您的模型PropertyFacility Property

附加has_many :property_facilities :through=>:assocs个关联。

以上简单地将PropertyFacilityparams推送到@property,您可以根据需要进行其他验证。