Rails 4 find or create by method doesn't work Rails 4 find or create by method doesn't work ruby-on-rails ruby-on-rails

Rails 4 find or create by method doesn't work


Please take a look at this answer.

What used to be

@company = Company.find_or_create_by_name(name)

in Rails 4 is now

@company = Company.find_or_create_by(name: name)

Another way to do this in Rails 4 would be:

@company = Company.where(name: name).first_or_create


Company.find_or_create_by(name: name)

It should work out of the box. Only thing that can prevent it from creating record is validation errors.

Try this in rails console to check if its working or not. And check the validation errors as well.

name = "YOUR TEXT FOR NAME ATTRIBUTE"c = Company.find_or_create_by(name: name)puts c.errors.full_messages


This method is deprecated in rails 4.

Rails4 release message:

Deprecated the old-style hash based finder API. This means that methods which previously accepted "finder options" no longer do.

It is deprecated method, but it should work. Maybe, Rails is not supporting it now.

You can get more info click here and check 11.2 Deprecations.