Rails after_create callback cannot access model attributes

I can’t access my model attributes in the after_create callback ... it looks like I should have the right?

controller:

@dog = Dog.new(:color => 'brown', :gender => 'male') @dog.user_id = current_user.id @dog.save 

Model:

 class Dog < ActiveRecord::Base def after_create logger.debug "[DOG CREATED] color:#{color} gender:#{gender} user:#{user_id}" end end 

console: (all is well)

 >>Dog.last =>#<Dog id: 1, color: "brown", gender: "male", user_id: 1> 

log: (wtf !?)

 ... [DOG CREATED] color: gender:male user ... 

Some of my attributes appear, while others do not! Oh no! Does anyone know what I'm doing wrong? In the past, I have always been able to user after_create this way.

Note. The actual variable names and values ​​I used were different, but the methods and code are the same.

+4
source share
4 answers

Figured out my own problem.

One of the attributes was virtual, in which I used self.update_attribute ... oops!

 def price=(amt) self.update_attribute(:price_in_cents, (amt*100.0).to_i) end 

So, for the record, update_attribute will actually create a database record (and run after_create) if it is not already created.

Next time I will definitely send the full code!

+4
source

Try this instead:

 class Dog < ActiveRecord::Base def after_create(dog) logger.debug "[DOG CREATED] color:#{dog.color} gender:#{dog.gender} user:#{dog.user_id}" end end 
0
source

Try using after_save instead of after_create. not verified.

after_create () Called after Base.save for new objects that have not yet been saved (the record does not exist). Note that this callback is still wrapped in a transaction around the save. For example, if you call an external pointer at this moment, it will not see the changes in the database.

0
source

A macro style callback is probably the best idea, not just a method override. This allows you to simultaneously run several different methods on the life cycle (if you want). I think you need this:

 class Dog < ActiveRecord::Base after_create :dog_logger def dog_logger logger.debug "[DOG CREATED] color:#{self.color} gender:#{self.gender} user:#{self.user_id}" end end 
0
source

Source: https://habr.com/ru/post/1306267/


All Articles