Inverse_of does not work inside after_initialize

inverse_of doesn't seem to work inside after_initialize callback

class User < ActiveRecord::Base has_many :faces, :inverse_of => :user end class Face < ActiveRecord::Base belongs_to :user, :inverse_of => :faces after_initialize :init def init p user.object_id end end u = User.find(56) u.object_id => 70242500754120 u.faces.first.user.object_id Face Load (0.3ms) SELECT `faces`.* FROM `faces` WHERE `faces`.`user_id` = 56 LIMIT 1 User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 56 LIMIT 1 70242477010060 => 70242500754120 u.faces.first.user == u => true 

there are different objects inside the callback, but the external one is the same. It looks like a callback was called before the reverse magic was set.

Any suggestions on a workaround that allow you to access the same object inside the after_initialize callback? thank you

+4
source share
1 answer

The init method actually retrieves the user object from the database and returns it again.

Each time you initialize a face, the application will query the database for the user, create an instance of it, print object_id ... and forget it.

I would recommend using impatient user loading with scope:

 class Face belongs_to :user scope :with_user, -> { joins(:user) } end 

This will save database calls :)

0
source

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


All Articles