Q:

Why is ActiveRecord trying to delete the row corresponding to an object when it's deleted from an array?

Inside an AR object class definition (I'm not sure that's relevant, but I'm including that info in case it is), I have a method that collects an array of other AR objects and selectively deletes some of them inside a loop. Essentially:
class SomeApplicationModel < ActiveRecord::Base
  def user_method
    c_list = [array of c objects]
    p_list.each{|p|
      ... a bunch of logic to determine if c should be deleted
      c_list.delete(c)
    }
  end
end

When it hits c_list.delete(c), I get an error in the logs from a relation that includes c and p:
ActiveRecord::StatementInvalid - Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails (`stagingdb/c_p`, CONSTRAINT `c_p_ibfk_1` FOREIGN KEY (`cp_id`) REFERENCES `cs` (`id`)): DELETE FROM `cs` WHERE `cs`.`id` = 147:

Why is it trying to delete the record in the db that corresponds to c here (the stack trace pegs the .delete line as where the error is thrown)?

A:

If c_list is an ActiveRecord::Relation instead of an Array, then delete will remove the value from the database.  You may want to check the value of c_list.class.  Depending on what you want to do, you could either use to_a to work with an Array or translate your filtering logic into a set of ActiveRecord::Relation methods.

