sql - Rails deleting a returned relation from subtraction of two queries -
i have 3 models
class business relationship 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
i have suppliers can inputted individually or in mass through excel.
when supplier deleted individually remove link_requests belong it. have method delete suppliers in mass through sql query. link_requests left behind. have updated query handle exception end whole bunch of dead data.
this way can figure out how find 'dead data'.
linkrequest.where(account_id: current_account)
homecoming link_requests belonging current_account, have deleted suppliers , ones existing suppliers, activerecord::relation
.
then can call: current_account.link_requests
homecoming link_requests existing suppliers, => activerecord::relation
there no attribute link_request
has can separate ones existing suppliers , ones deleted suppliers. can't phone call invalid ones, way know valid because current_account gets link_requests through existing suppliers.
so initial thought subtract valid ones sum total of link_requests way left 'invalid requests' , phone call destroy_all on them.
only when subtract 2 relations array.
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 invalid ones. dead_links = (linkrequest.where(acconut_id: current_account) - current_acconut.link_requests) dead_links.class => array
there no way can phone call destroy_all on array since in has no relation suppliers db anymore. !! #<nomethoderror: undefined method 'destroy_all' #<array:0x007fdb59a67728>>
to compare every link_requests supplier_id existing suppliers db , delete ones don't match expensive operation, since db has hundreds of millions of both info types. thinking of creating before filter on linkrequests controller delete them current business relationship when runs indexing action.
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
something this.. other ideas much appreciated, hoping find way relation object after comparing 2 query's , able deed on that.
thanks help!
i think trick:
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
sql ruby-on-rails ruby database-relations
No comments:
Post a Comment