一)使用協會:
class Market < AR::Base
# * note that if you are not dealing with a legacy schema, you should
# rename user_id to market_id and remove the foreigh_key assignment.
# * dependent => :destroy is important or you'll have orphaned records
# in your database if you ever decide to delete some market
has_many :energy_potions, :foreign_key => :user_id, :dependent => :destroy
end
class EnergyPotion < AR::Base
belongs_to :market, :foreign_key => :user_id
end
二)不需要添加每一個後重新加載的關聯。也移動功能 到模型:
find_or_create_market.restock
class Market
def restock
# * note 4, not 5 here. it starts with 0
(market.energy_potions.size..4).each {market.energy_potions.create!}
end
end
C)也注意到創造!而不是創造。 你應該檢測錯誤。 錯誤處理取決於應用程序。 你的情況,因爲你從cron運行它可以做幾件事 *發送電子郵件與警報 *捕獲異常並記錄它們,(exception_notifier插件,或hoptoad託管服務) *打印到stderror和配置cron發送錯誤一些郵件。
def self.restock_potions
market = find_or_create
market.restock
rescue ActiveRecord::RecordInvalid
...
rescue
...
end
是的,這看起來接近我之後的解決方案,但有沒有辦法一次保存所有新葯?例如,創建您需要的額外3,然後只進行一次數據庫調用?或者這只是想微觀優化? – Kirschstein 2009-04-13 18:35:51