2015-10-14 39 views
2

我想知道是否有軌道方式來銷燬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

如果表格目前不存在,我會建議創建一個migrat以創建連接表。然後寫一個rake任務來填充它。 – onebree

回答

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創建一個

+0

這意味着我必須爲買家中的每條記錄運行查詢。有沒有辦法在單個連接查詢中完成它? – leemour

+0

@leemour查看與1位買家合作的更新答案,並與所有Bueyrs –