0
在應用程序中,國家模型包含許多城市,並且有兩種方法可在所有城市執行操作。對模型關聯對象執行批量操作
class Country < ActiveRecord::Base
has_many :cities
def destroy_cities
self.cities.each do |city|
city.destroy
end
end
def update_cities(new_status)
self.cities.each do |city|
city.status = new_status
end
end
end
我不知道是否有更簡單的方法來寫這些方法,就像一個不存在的self.cities.destroy
和self.cities.status = new_status
對效率的角度來看,它會執行這些SQL查詢:
DELETE FROM cities WHERE country_id=#{country_id}
UPDATE cities SET status=#{new_status} WHERE country_id=#{country_id}
而不是運行多個查詢:
SELECT * FROM cities WHERE country_id=#{country_id}
DELETE FROM cities WHERE id=#{city_ids[0]}
DELETE FROM cities WHERE id=#{city_ids[1]}
DELETE FROM cities WHERE id=#{city_ids[2]}
...
謝謝。這非常有幫助。 – rickypai 2012-03-22 06:14:07
很高興我能幫忙:) – Jamsi 2012-03-22 09:59:21