我从3.2升级到Rails4.我有以下查询:
progress = Progress.find_or_initialize_by_chore_id_and_period_and_account_id(chore.id, period[chore.frequency], chore.account_id)
Run Code Online (Sandbox Code Playgroud)
在运行测试时,我收到了弃用警告
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)
Run Code Online (Sandbox Code Playgroud)
所以,我更新了我的查询如下:
progress = Progress.where('chore.id' => 'chore_id', 'period[chore.frequency]' => 'period', 'chore.account_id' => 'account_id').first_or_initialize
Run Code Online (Sandbox Code Playgroud)
但它不起作用.我的查询是否正确?
我真的很喜欢这个first_or_create方法:
# Find the first user named Scarlett or create a new one with a particular last name.
User.where(:first_name => 'Scarlett').first_or_create(:last_name => 'Johansson')
# => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
Run Code Online (Sandbox Code Playgroud)
我想知道如果不存在或不同,我如何也可以使用last_name'Johannson'更新用户.寻找最简洁的方法.与上述类似的单衬里将是理想的.
一种可能的方法是使用first_or_initialize和update_attributes.我对这种方法唯一关注的是,即使在提供的字段上有100%的匹配,它也会运行更新.