Ruby-on-rails find_or_initialize_by 方法的 Rails4 弃用警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22472584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails4 Deprecation warning for find_or_initialize_by method
提问by Amrit Dhungana
I am upgrading to Rails4 from 3.2. I have the following query:
我正在从 3.2 升级到 Rails4。我有以下查询:
progress = Progress.find_or_initialize_by_chore_id_and_period_and_account_id(chore.id, period[chore.frequency], chore.account_id)
While running test, I am getting deprecation warning
在运行测试时,我收到弃用警告
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)
So, I have updated my query as follows:
所以,我更新了我的查询如下:
progress = Progress.where('chore.id' => 'chore_id', 'period[chore.frequency]' => 'period', 'chore.account_id' => 'account_id').first_or_initialize
But its not working. Is my query correct ?
但它不起作用。我的查询正确吗?
回答by rails4guides.com
You can use the following:
您可以使用以下内容:
Progress.find_or_initialize_by(chore_id: chore.id, period: period[chore.frequency], account_id: chore.account_id)
回答by Magne
# 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
NB: In these cases, the word 'initialize' will be like calling Team.new. You can also replace 'initialize' 'create' to instead call Team.create, like this: .find_or_create_byor .first_or_create
注意:在这些情况下,“初始化”这个词就像调用Team.new. 您也可以替换“初始化”“创造”,改为调用Team.create,像这样:.find_or_create_by或.first_or_create
Expanded and improved, but based on: http://blog.remarkablelabs.com/2012/12/what-s-new-in-active-record-rails-4-countdown-to-2013
扩展和改进,但基于:http: //blog.remarkablelabs.com/2012/12/what-s-new-in-active-record-rails-4-countdown-to-2013

