ActiveRecord::ActiveRecordError (cannot touch on a new record object) rails 4

Viewed 1340

I recently upgraded a rails 3 application to rails 4. When I am trying to create a new Test, below code from before_save fails to execute. The same code works fine with rails 3.

class Test < ActiveRecord::Base
  has_many  :assignments, :dependent => :destroy

  before_save do
    if code_changed? 
      self.assignments.each{|a| a.touch}
    end
  end
end

class Assignment < ActiveRecord::Base
  belongs_to :test, :touch => true
end

I see the below error when I create a new test.

ActiveRecord::ActiveRecordError (cannot touch on a new record object):
app/models/test.rb:6:in `block (2 levels) in <class:Test>'
app/models/test.rb:6:in `block in <class:Test>'
app/controllers/tests_controller.rb:423:in `create'

Any suggestions to resolve this issue ??

2 Answers
Related