I want to see if I’m not missing something with associations and eager
loading. (I’m currently using Locomotive on OS X and SQLite3.)
I have two simple tables/models, set up properly: teams has_many
:matches and matches belongs_to :teams. Matches has a match number and
a team_id field (along with several other fields) and teams has a
team_number field (again, along with several other fields.)
I want to get a list of all the matches with only one piece of data
from teams (there are about 360 rows in the matches table).
I did this and it works, but is a little slow:
@matches = Match.find(:all, :order => ‘number’)
and I loop through it in the view and display the match number and the
team number, along with the usual “show”, “edit”, and “destroy” links.
This works, but in the log it generates a SQL Select statement for
each line - 360 times. If I change to:
@matches = Match.find(:all, :include => ‘team’, :order => ‘number’)
it only generates one SQL call, but it is including all fields from
both tables and doesn’t reduce the time to generate the page (which is
on the order of almost 10 seconds - remember only 360 records.)
Now, if I change to this:
@matches = Match.find_by_sql(‘select matches.“id”,
teams.“team_number”, matches.“number” from matches left outer join
teams on teams.id = matches.team_id order by number’)
it works much faster (though I did have to change how I accessed the
team number from “match.team.team_number” to “match.team_number” -
less code is good )
I’m just curious if I’m missing something that would make a “plain”
find not return all of the fields. I tried using :select, but that
didn’t make a difference, nor change the actual SQL call.
Thanks for any info!