Skip to content

add explicit inverse_of to scoped user_levels association#10745

Merged
wjordan merged 1 commit into
stagingfrom
inverse_of_user_levels
Sep 20, 2016
Merged

add explicit inverse_of to scoped user_levels association#10745
wjordan merged 1 commit into
stagingfrom
inverse_of_user_levels

Conversation

@wjordan

@wjordan wjordan commented Sep 20, 2016

Copy link
Copy Markdown
Contributor

Rails ActiveRecord has an optimization-feature called 'inverse associations' (see "Setting Inverses" API documentation), which optimizes query chains such as parent -> child -> parent going between has_many and belongs_to associations e.g., user.user_levels[0].user, by reusing the original ActiveRecord object rather than re-querying the database to recreate it.

Since Rails 4.1, ActiveRecord tries to automatically infer inverse_of relations based on the class names- however, custom scopes (such as -> {order 'id desc'}) cause the automatic inference to be disabled, so they need to be explicitly added in order for this optimization to be applied.

Before:

irb(main):001:0> User.first.user_levels.first.user
  User Load (0.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`deleted_at` IS NULL ORDER BY `users`.`id` ASC LIMIT 1
  UserLevel Load (0.3ms)  SELECT  `user_levels`.* FROM `user_levels` WHERE `user_levels`.`user_id` = 1 ORDER BY id desc LIMIT 1
  User Load (0.4ms)  SELECT  `users`.* FROM `users` WHERE `users`.`deleted_at` IS NULL AND `users`.`id` = 1 LIMIT 1

After:

irb(main):001:0> User.first.user_levels.first.user
  User Load (0.9ms)  SELECT  `users`.* FROM `users` WHERE `users`.`deleted_at` IS NULL ORDER BY `users`.`id` ASC LIMIT 1
  UserLevel Load (0.9ms)  SELECT  `user_levels`.* FROM `user_levels` WHERE `user_levels`.`user_id` = 1 ORDER BY `user_levels`.`id` ASC LIMIT 1

@ashercodeorg

Copy link
Copy Markdown
Contributor

LGTM.

@ashercodeorg

Copy link
Copy Markdown
Contributor

Should we do an audit and see if there is anywhere else in our codebase missing such an annotation?

@wjordan

wjordan commented Sep 20, 2016

Copy link
Copy Markdown
Contributor Author

yeah, i think an audit-pass through our ActiveRecord models for this sort of easy optimization could be helpful.

@wjordan wjordan merged commit b18f280 into staging Sep 20, 2016
@wjordan wjordan deleted the inverse_of_user_levels branch September 20, 2016 23:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants