2014-10-29 71 views
0

的减法返回的关系,我有三个型号Rails的删除从两个查询

class Account 
    has_many :link_requests, :through => :suppliers 
end 

class Supplier 
    has_many :link_requests, :dependent => :destroy 
end 

class LinkRequest 
    belongs_to :supplier 
    belongs_to :account 
end 

我有它使供应商可以单独或批量到Excel输入。

当供应商被单独删除时,它将删除属于它的所有link_requests。但是我们有一种方法可以通过SQL查询批量删除所有供应商。但是所有的link_request都被留下了。我现在更新了查询,以便它能处理这个异常,但现在我们最终得到了大量的死亡数据。

这真的是我能找出如何找到'死亡数据'的唯一方法。

LinkRequest.where(account_id: current_account) 将返回属于current_account的所有link_request,那些已删除供应商和已有供应商的link_request,作为ActiveRecord::Relation

那么我就可以拨打电话:current_account.link_requests这将返回所有link_requests与现有的供应商,也可作为=> ActiveRecord::Relation

没有属性的link_request具有可与现有的供应商和那些与删除供应商分开的。所以我不能只调用所有无效的,唯一的方法是我知道它们是有效的,因为current_account通过其现有的供应商获得它的link_requests。

所以我最初的想法是从所有link_requests的总和中减去所有有效的那个,这样我就会留下所有'无效请求'并且在它们上调用destroy_all。

只有当我减去两个关系,我得到一个数组。

LinkRequest.where(account_id: current_account).count 
    => 10 
current_account.link_requests.count 
    => 4 

(LinkRequest.where(acconut_id: current_account) - current_acconut.link_requests).count 
    => 6 #these are all the invalid ones. 

dead_links = (LinkRequest.where(acconut_id: current_account) - current_acconut.link_requests) 
dead_links.class 
    => Array 

没有办法的话,我可以因为在调用destroy_all阵列上没有任何关系的供应商数据库了。我得到!! #<NoMethodError: undefined method 'destroy_all' for #<Array:0x007fdb59a67728>>

要比较每个link_requests supplier_id与现有供应商数据库,然后删除不匹配的数据库将是一个非常昂贵的操作,因为数据库有数以百万计的两种数据类型。所以我想在LinkRequests控制器上创建一个之前的过滤器,当他运行索引操作时,它将删除它们的当前帐户。

private 
    def clean_up_boogle_link_requests 
     @dead_requests = LinkRequest.where(account_id: current_account) - current_account.manual_boogle_link_requests 
     @dead_requests.delete_all if !dead_requests.empty? 
    end 

这样的事情..任何其他想法将非常感激,我希望能找到一种方法比较两个查询的后能得到一个关系对象回来,然后才能够采取行动上。

感谢您的帮助!

回答

1

我认为这将这样的伎俩:

dead_link_ids = LinkRequest.where(acconut_id: current_account).pluck(:id) - 
    current_acconut.link_requests.pluck(:id) 
LinkRequest.where(id: dead_link_ids).delete_all 
+0

谢谢指点先生。它现在如此简单,以至于它在我面前。 – TheLegend 2014-10-29 20:05:25