The Somewhat-Extremely-Helpful inverse_of Option
By: Johnathon Wright on: October 04, 2012
Let's say you have the following association set up:
class Route < ActiveRecord::Base hasmany :appointments, :inverseof => :route # long live the hash rocket! end
class Appointment < ActiveRecord::Base belongsto :route, :inverseof => :appointments
end
the 'inverse-of' option is supposed to prevent unneeded queries.
If you ask a route for one of its appointments, and then ask that appointment for its route, there's no need to issue a query... the route is already in memory. Without inverse_of, though, it will go to the db. Say it with me boys and girls, "Lack of referential integrity."
r = Route.find 10
Route Load (0.2ms) SELECT * FROM routes
WHERE (routes
.id
= 10)
a = r.appointments.first
Appointment Load (1.2ms) SELECT * FROM appointments
WHERE (appointments
.route_id = 10)
a.route
Route Load (0.2ms) SELECT * FROM routes
WHERE (routes
.id
= 10)
WHERE IS MY AWESOMENESS????
It turns out this only works if you use array indexes.
r = Route.find 10
Route Load (0.2ms) SELECT * FROM routes
WHERE (routes
.id
= 10)
a = r.appointments[0]
Appointment Load (1.2ms) SELECT * FROM appointments
WHERE (appointments
.route_id = 10)
a.route
Route Load (0.2ms) SELECT * FROM routes
WHERE (routes
.id
= 10)
h2. References
"inverseof not working with hasmany":https://github.com/rails/rails/issues/3223