8

レール2.3.8。ユーザー、ソース、サブスクリプションの3つのモデルがあります。

User  attr_accessible   :source_ids
             has_many   :subscriptions
             has_many   :sources, :through => :subscriptions

Source       has_many   :subscriptions

Subscription belongs_to :user
             belongs_to :source

ユーザーがソースへのサブスクリプションを編集できるようにするインターフェースがあります。source_idsを収集し、その収集に基づいてサブスクリプションを作成または削除します。私が抱えている問題は、引用です:

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

サブスクリプションは破棄されるのではなく、削除されます。サブスクリプションモデルにトリガーされないコールバックがあります:

before_destroy do |subscription|
  [Some irrelevant object not to be mentioned].destroy
end

私の質問は、加入モデルが原因でサブスクリプションが自動的に削除されたときに、このコールバックをトリガーするにはどうすればよいですか?

4

2 に答える 2

7

HMTでの返信への返信collection_singular_ids=結合モデルの削除は直接であり、破棄コールバックはトリガーされません

この行を変更します。

 has_many :users, :through => :memberships

これに:

 has_many :users, :through => :memberships, :after_remove => :your_custom_method

そして、ユーザーモデルで保護されたyour_custom_methodを定義します。このように、ユーザーがソースへのサブスクリプションを削除すると、このメソッドが呼び出されます。

幸運を!

于 2011-01-31T00:45:43.207 に答える
3
@user.subscriptions.delete
has_many   :subscriptions, :dependent => :destroy    # <- setting this on the association  will destroy the related subscriptions
has_many   :subscriptions, :dependent => :delete_all # <- setting this on the association  will delete the related subscriptions

rdocから:

collection.delete(object、…)
外部キーをに設定して、コレクションから1つ以上のオブジェクトを削除しますNULL。オブジェクトは、に関連付けられている場合はさらに破棄され、に関連付けられて:dependent => :destroyいる場合は削除されます:dependent => :delete_all

于 2011-01-29T23:52:56.857 に答える