On Jul 4, 12:59 am, Dallas <[email protected]> wrote:
> 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
>

Associations aren't attributes :-) There's a few bits of state you
need to fake up to convince AR that it has loaded an association. The
canonical example of this is probably the stuff in
association_preload.rb in Rails itself.

Fred
> 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!
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to