Created
September 14, 2010 04:01
-
-
Save abscondment/578513 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def Restaurant.add_cuisines(restaurants) | |
return [] if restaurants.empty? | |
ids = [] | |
id_map = {} | |
restaurants.each do |r| | |
id_map[r[:id]] = r | |
ids << r[:id] | |
# make sure ActiveRecord won't try to load cuisines again | |
r.cuisines.loaded | |
end | |
# make sure we load each Cuisine once | |
cuisine_map = Hash.new {|h,id| h[id] = Cuisine.find(id)} | |
RestaurantCuisine.find(:all, | |
:conditions => ["restaurant_id in (?)", ids]).each do |row| | |
# use the association target so we don't do an insert | |
id_map[row[:restaurant_id]].cuisines.target << cuisine_map[row[:cuisine_id]] | |
end | |
return restaurants | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment