2015-10-14 38 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 –