I want to destroy all objects that have parent_type == 'Profile'
or child_type == 'Profile'
, like this:
Relationship.destroy_all(:parent_type => "Pro开发者_JS百科file")
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
Use a SQL condition instead of a hash:
Relationship.destroy_all("(parent_type = 'Profile') OR (child_type = 'Profile')")
精彩评论