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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.