Rails: Attempted to destroy a stale object
I'm trying to delete an object hierarchy via:
where Foo has this dependency in ./app/models/foo.rb:
has_many :bars, :dependent => :destroy
but Rails is returning me this error:
Attempted to destroy a stale object: Bar
Objects where duplicated manually (via SQL) and the `lock_version' field was left NULL. Setting the lock_version to 0 on the newly inserted objects made the error disappear.
When running the command
Foo.find_by_id(1).delete in the Rails console, I saw the this SQL command being executed just before the error:
SQL (0.2ms) DELETE FROM "bars" WHERE ("bars"."id" = 123 AND "bars"."lock_version" = 0) (0.1ms) ROLLBACK ActiveRecord::StaleObjectError: ActiveRecord::StaleObjectError
And I released I'd left
lock_version to NULL.