0

I'm trying to override a has_many association getter using a method.

I have a has_many association for cards via join table user_cards. I added a method into the model... trying to completely override the conditions.

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

The user_cards is polymorphic so there's a source and a source_type from the association call.

The getter looks okay... as expected.

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

However... the simple deletion of associated record(s) is now deleting the original, not just the join table records which is very scary and can destroy the app.

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

The above deletes the @card object completely from the database... I'm expecting it to delete the @user.user_cards record.

I'm not familiar in overriding association getter... Please help. Thanks.

Ilya Lavrov
  • 2,810
  • 3
  • 20
  • 37
rukia_kuchiki_21
  • 1,279
  • 3
  • 17
  • 34
  • Possible duplicate of [How to use dependent: :destroy in rails?](http://stackoverflow.com/questions/29560805/how-to-use-dependent-destroy-in-rails) – yoones Apr 26 '17 at 09:51

1 Answers1

0

Easy way to solve this problem is to destroy UserCard directly.

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

But ensure that UserCard does not have dependent: destroy

nautgrad
  • 414
  • 2
  • 8