Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Destroying already destroyed object with touch association causes "can not touch on a new record object" error #13445

Closed
ronalchn opened this Issue Dec 22, 2013 · 2 comments

Comments

Projects
None yet
3 participants
@ronalchn
Copy link

commented Dec 22, 2013

The following test fails: https://gist.github.com/ronalchn/8078852

Trying to destroy an object which was already automatically destroyed by its parent causes the error.

class Post < ActiveRecord::Base
  has_many :comments, dependent: :destroy, inverse_of: :post # setting inverse does not change behaviour of tests
end

class Comment < ActiveRecord::Base
  belongs_to :post, touch: true, inverse_of: :comments
end

class BugTest < Minitest::Unit::TestCase
  def test_association_failing
    comment = Comment.create(post: Post.new)
    comment.post.destroy
    comment.destroy #=> ActiveRecord::ActiveRecordError: can not touch on a new record object
  end
  def test_comment_destroyed
    comment = Comment.create(post: Post.new)
    comment.post.destroy
    refute comment.persisted?, 'destroying post should destroy comment' #=> true
  end
end

Normally, destroying an already destroyed object doesn't throw any errors, so this race condition should also not throw an error.

Note that comment remains persisted even after its parent is destroyed. Actually, it is not a big problem if it things it still is persisted (which would be the case without the inverse_of option), but it shouldn't cause the touch error.

Also note the inconsistent behaviour that occurs when comment is reloaded before destroying the post.

Relevant issues are: #9320 and #9443


Workaround:

comment.clear_association_cache
comment.destroy #=> doesn't throw error anymore
@pftg

This comment has been minimized.

Copy link
Contributor

commented Dec 22, 2013

Thanks for your report, I'm on finishing my PR with fix for this issue. Some notes about refute comment.persisted? which I will fix in another PR.

@carlosantoniodasilva

This comment has been minimized.

Copy link
Member

commented Dec 23, 2013

Closed on master by #13455, thanks for reporting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.