I have a model Tweets, it has_many :teams
I wrote a custom find_by_sql query for tweets (yes i tried all other
approaches) such that I can’t eager load the teams. I collect the ids
and try to fake eager loading myself like so…
team_hash = {}
#collect up the tweet ids
tweet_ids = tweets.collect{|t| t.id}
#find the associated teams
TeamTweet.find(:all, :include => :team, :conditions => “tweet_id IN (”
- tweet_ids.join(’,’) +")").each do |tt|
team_hash[tt.tweet_id] = team_hash[tt.tweet_id] ? team_hash
[tt.tweet_id] << tt.team : [tt.team]
end
#reset the teams attribute
tweets.each do |tweet|
teams = team_hash[tweet.id] ? team_hash[tweet.id] : []
tweet.write_attribute(:teams, teams)
also tried tweet.teams = teams
end
I’m not sure f there is a better way to do this in general but when I
access tweet.teams it still queries the database for the teams on each
tweet even though I set it already. I assumed this would be a common
problem for people using find_by_sql but can’t find anything. Any
solutions or suggestions would be greatly appreciated!