Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `find_or_initialize' for a Relation

I've migrated to Rails 4 from Rails 3.2. I had this:

  MyModel.find_or_initialize_by_field1("fdsfdsfds")

Now I have this

  MyModel.where(field1: "fdsfdsfds").find_or_initialize

which now causes an exception in the tests:

   undefined method `find_or_initialize' for #<ActiveRecord::Relation []>

But in the guide it says nothing about what else should be there. How to fix it?


1 Answers

That's happening because when the returned result is an empty array you can't call the find_or_initalize method on it. Try:

   MyModel.where(field1: 'asdfasdfasdf').first_or_initialize
like image 148
bkunzi01 Avatar answered Dec 30 '25 23:12

bkunzi01



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!