我想知道在给定条件的情况下是否存在用于销毁has_many关联的rails方法。 的买方
class Buyer < ActiveRecord::Base
has_many :phones, as: :phoneable, dependent: :destroy, class_name: 'Telephone'
end
电话
class Telephone < ActiveRecord::Base
belongs_to :phoneable, polymorphic: true
end
我想通过电话加入买家并销毁所有电话where('buyers.tel = telephones.number')
。编写此查询的最佳方式是什么?
答案 0 :(得分:1)
如果你只处理1 Buyer
条记录:
buyer = Buyer.first
buyer.phones.where('number = ?', buyer.tel).destroy_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)
请注意,我们添加phoneable_type = 'Buyer'
条件,因为您具有多态关系,而您只需要为Buyer
创建的条件