3

たとえば、次のモデルがあるとします。

class Campaign < ActiveRecord::Base
  has_many :targetings
  has_many :devices, :through => :targetings
  attr_accessible lalalala, :device_ids
end

class Device < ActiveRecord::Base
  has_many :targetings
  has_many :campaigns, :through => :targetings
end

class Targetings < ActiveRecord::Base
  belongs_to :campaign
  belongs_to :targeting
  has_many :docs, :dependent => :destroy
end

class Doc < ActiveRecord::Base
  belongs_to :targeting
end

結合モデル ( Targetings ) を使用した単純なCampaigns - Devices多対多関連付けです。ターゲティングには多くの関連ドキュメントがあり、ターゲティング破棄で破棄したいと考えています。

編集ページには、「campaign[device_ids]」という名前のチェックボックス セットがあり、現在のキャンペーンのデバイスを選択するために使用します。

私はCampaignに追加device_idsし、Rails はCampaignDevicesの間の関連付けを何らかの形で管理できました。それは暗黙的にTargetingモデルを作成します。attr_acessible

ただし、Campaign と Device の関連付けを削除すると、Targeting モデルは破棄されますが、その Targeting に関連付けられたドキュメントは破棄されません。

例:

Devices: 
  id: 1
  title: A
  ----
  id: 2
  title: B

Campaigns:
  id: 1
  title: CA

Targetings:
  id: 1
  device_id: 1
  campaign_id: 1

Docs:
  id: 1
  content: lalala
  targeting_id: 1

それが初期状態です。私が要求するとき POST campaign/1/update:device_ids = [2]

Targetings:
  id: 2
  device_id: 2
  campaign_id: 1

それでも

Docs:
  id: 1
  content: lalala
  targeting_id: 1

そのため、Targetings[id=1] は削除されましたが、依存するドキュメントは削除されませんでした。

それは期待される動作ですか?関連付けを手動で更新する必要がありますか? もしそうなら、それを行う正しい方法は何ですか?

PSターゲティングは常に暗黙的に作成する必要があります。

4

1 に答える 1

3

のようです(公式ドキュメントから

結合モデルの自動削除は直接行われ、破棄コールバックはトリガーされません。

一見すると明らかな決定ではありません - パフォーマンス上の理由からそうなったと思います。after_removeただし、デバイスの関連付けにフックを使用することで、上記の問題を解決できました。

has_many :devices, :through => :targetings, :before_remove => :destroy_targeting

def destroy_targeting(device)
    Targeting.where(campaign_id: id, device_id: device.id).destroy_all
end
于 2013-06-28T10:42:12.443 に答える