2017-04-26 80 views
0

我想重寫一個has_many關聯getter使用方法。刪除相關的記錄刪除原來的Rails中的has_many關聯getter後

我有一個has_many卡通過連接表user_cards協會。我在模型中添加了一個方法...嘗試完全覆蓋條件。

has_many :cards, through: :user_cards, source: :canonical, source_type: 'Primary' 

user_cards是多態的所以有source,並從聯想呼叫source_type

吸氣劑看起來沒問題......正如所料。

def cards 
    Card.where(id: user_cards.pluck(:card_id)) 
end 

但是......相關結果的簡單刪除正在刪除原來的,而不僅僅是連接表的記錄,這是非常可怕的,會破壞應用程序。

@card = Card.find(1) 
@user.cards.delete(@card) 

以上從數據庫中完全刪除@card對象......我期待它刪除@user.user_cards記錄。

我不熟悉重寫協會getter ...請幫助。謝謝。

+0

的可能的複製[如何使用依賴於:在軌摧毀?](http://stackoverflow.com/questions/29560805/how-to-使用依賴,破壞式護欄) – yoones

回答

0

解決此問題的簡單方法是直接銷燬UserCard

@card = Card.find(1) 
@card.user_cards.where(user_id: @user.id).destroy 

但確保UserCard沒有dependent: destroy