Rails4对find_or_initialize_by方法的弃用警告
我从3.2升级到Rails4。 我有以下查询:
progress = Progress.find_or_initialize_by_chore_id_and_period_and_account_id(chore.id, period[chore.frequency], chore.account_id)
在运行测试时,我收到了弃用警告
DEPRECATION WARNING: This dynamic method is deprecated. Please use eg Post.find_or_initialize_by(name: 'foo') instead. (called from bump_progress at /Users/newimac/RailsApp/bank/app/models/child.rb:200)
所以,我更新了我的查询如下:
progress = Progress.where('chore.id' => 'chore_id', 'period[chore.frequency]' => 'period', 'chore.account_id' => 'account_id').first_or_initialize
但它不起作用。 我的查询是否正确?
您可以使用以下内容:
Progress.find_or_initialize_by(chore_id: chore.id, period: period[chore.frequency], account_id: chore.account_id)
# find_or_initialize_by_ # Rails 3: Team.find_or_initialize_by_name('Justice League') # Rails 4: Team.find_or_initialize_by(name: 'Justice League') # or Team.where(name: 'Justice League').first_or_initialize
注意:在这些情况下,’initialize’一词就像调用Team.new
,但’initialize’可以替换为’create’,就像调用Team.create
一样,如下所示: .find_or_create_by
或.first_or_create
扩展和改进,但基于: http : //blog.remarkablelabs.com/2012/12/what-s-new-in-active-record-rails-4-countdown-to-2013