20

I am upgrading to Rails4 from 3.2. I have the following query:

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 ?

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
Amrit Dhungana
  • 4,371
  • 5
  • 31
  • 36

2 Answers2

31

You can use the following:

Progress.find_or_initialize_by(chore_id: chore.id, period: period[chore.frequency], account_id: chore.account_id) 
rails4guides.com
  • 1,441
  • 2
  • 11
  • 8
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

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_by or .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

Magne
  • 16,401
  • 10
  • 68
  • 88