Skip to content

Instantly share code, notes, and snippets.

@abscondment
Created September 14, 2010 04:01
Show Gist options
  • Save abscondment/578513 to your computer and use it in GitHub Desktop.
Save abscondment/578513 to your computer and use it in GitHub Desktop.
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