我从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 e.g. 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
但它不起作用。我的查询是否正确?
答案 0 :(得分:28)
您可以使用以下内容:
Progress.find_or_initialize_by(chore_id: chore.id, period: period[chore.frequency], account_id: chore.account_id)
答案 1 :(得分:14)
# 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
注意:在这些情况下,单词'初始化'就像打电话给Team.new
一样。您也可以替换'初始化' '创建'而是拨打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