Lance Pollard
Lance Pollard

Reputation: 79480

One SQL Call for destroying records with property "a" or "b" in ActiveRecord?

I want to destroy all objects that have parent_type == 'Profile' or child_type == 'Profile', like this:

Relationship.destroy_all(:parent_type => "Profile")
Relationship.destroy_all(:child_type => "Profile")

How do I combine that into one method and one sql call?

Went with something like this:

class Group < ActiveRecord::Base
  has_many :relationships

  after_destroy :destroy_relationships

  def destroy_relationships
    conditions = %Q|(`relationships`.parent_type IN ("#{self.class.name}","#{self.class.base_class.name}") AND `relationships`.parent_id = #{self.id}) OR (`relationships`.child_type IN ("#{self.class.name}","#{self.class.base_class.name}") AND `relationships`.child_id = #{self.id})|
    Relationship.delete_all(conditions)
  end
end

Upvotes: 2

Views: 45

Answers (1)

ddrew
ddrew

Reputation: 36

Use a SQL condition instead of a hash:

Relationship.destroy_all("(parent_type = 'Profile') OR (child_type = 'Profile')")

Upvotes: 2

Related Questions