Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

has_one and belongs_to loading too much

#4158
class User < ActiveRecord::Base
  has_one :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end
?> current_user.profile.user.profile.user.profile.user.profile
  User Load (0.4ms)   SELECT * FROM `users` WHERE (`users`.`id` = 4)
  Profile Load (0.1ms)   SELECT * FROM `profiles` WHERE (`profiles`.user_id = 4) LIMIT 1
  User Load (0.1ms)   SELECT * FROM `users` WHERE (`users`.`id` = 4)
  Profile Load (0.1ms)   SELECT * FROM `profiles` WHERE (`profiles`.user_id = 4) LIMIT 1
  User Load (0.1ms)   SELECT * FROM `users` WHERE (`users`.`id` = 4)
  Profile Load (0.1ms)   SELECT * FROM `profiles` WHERE (`profiles`.user_id = 4) LIMIT 1

This one-liner is obviously just an demonstration of the issue. The actual situation this was discovered in was a few user methods which call methods on the profile which call methods on the user, etc.

The reflections could be aware of the symmetry and connect the two objects, preventing further loading.

Reported by Greg Hazel · March 12th, 2010 @ 10:38 AM

State: invalid
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. José Valim
    José Valim
    • State changed from new to invalid

    You need to use inverse_of.

    has_one :profile, :inverse_of => :user

    And vice-versa.

    March 12th, 2010 @ 06:23 PM