leemour
leemour

Reputation: 12003

Rails - destroy a 'join table' association where

I wonder if there is a rails way to destroy a has_many association, given a condition. buyer

class Buyer < ActiveRecord::Base
  has_many :phones, as: :phoneable, dependent: :destroy, class_name: 'Telephone'
end

telephone

class Telephone < ActiveRecord::Base
  belongs_to :phoneable, polymorphic: true
end

I want to join Buyers with Telephones and destroy all telephones where('buyers.tel = telephones.number'). What's the best way to write this query?

Upvotes: 2

Views: 97

Answers (1)

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

if you to handle that for only 1 Buyer record:

buyer = Buyer.first
buyer.phones.where('number = ?', buyer.tel).destroy_all

if for all Buyers:

# XXX this will select all buyers you want but in your case you want to destroy the phones not the buyers so we need the reverse one check next:
Buyer.joins(:phones).where("buyers.tel = telephones.number")

# but this one will as we need the reverse relation:
Telephone.where("phoneable_type = 'Buyer' and buyers.tel = telephones.number").includes(:phoneable)

Note we add a condition that phoneable_type = 'Buyer' as you have a polymorphic relation and you you only need the one which created for Buyer only

Upvotes: 1

Related Questions