dimanche 27 janvier 2019

why after_add in rails 5 is executing method without an object is being created

I am not able to understand why after_add is executing method before object is being created.

Suppose I have a class User

class User << ActiveRecord::Base
  has_many :subjects, after_add: :create_user_subject

  def create_user_subject
    Subject.create!(user_id: self.id,......) 
  end
end 

So when I am trying to create user object.

user = User.new(name: 'some name')
user.save

then it is throwing an error

OCIError: ORA-01400: cannot insert NULL into ("subjects"."user_id")

Why it is trying to save an association subjects before user object is created. It was working in rails 3 why the functionality is changed in rails 5 and what are the alternatives. Thanks

Aucun commentaire:

Enregistrer un commentaire