Working with a relatively large data set I have a situation where I need to load data with an associated table and later on in the process the associated objects need to call back to the first object. However it does not seem to fill in the back-reference to the object and so even using :include it has many sql queries
For example:
class Movie
belongs_to :title
end
class Title
has_one: movie
end
First, I load the data via
Movie.all(:include => [ :title ])
This results in two sql queries. One to load all the movies, and the one to load all the titles by id.
Second (for purposes of simple demonstration) I want to use the title to get back the movie.
movies.collect{ |movie|
cur_title = movie.title
back_reference = cur_title.movie
}
This is where the problem lies. I’d assume no further queries would be necessary as both sides of the one-to-one relationship where already loaded. However the second line in the collect causes many new queries to load each “movie” within the title. Is there a way to have rails automatically fill in this back-reference within title to avoid the many additional (redundant) queries or can this be done manually in an easy way?
Running under Rails 2.3.12
Rails 3.x has a mechanism called
:inverse_ofto specify the reverse association.namely;
in this case, you will not get the reload.
In Rails 2.x you may find @h-lame’s parental_control a useful temporary solution.