54

I have a one to many association between jobs and companies and it works fine. In the job form view I have text_field for the company name with an autocomplete feature. The autocomplete works fine but the find_or_create_by don't create a new company if I put a company name that doesn't exist in the autocomplete list.

  def company_name
    company.try(:name)
  end

  def company_name=(name)
    @company = Company.find_or_create_by(name: name)
  end
Coenwulf
  • 1,937
  • 2
  • 15
  • 23
Loenvpy
  • 899
  • 1
  • 10
  • 30
  • If i create a job and put a new company that did not exit in the companies list the new company will not be created – Loenvpy Mar 20 '14 at 14:59

3 Answers3

112

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
Community
  • 1
  • 1
eronisko
  • 1,862
  • 1
  • 15
  • 14
26
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
Kalpesh Fulpagare
  • 1,309
  • 10
  • 18
0

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.

Rick Smith
  • 9,031
  • 15
  • 81
  • 85
uma
  • 2,932
  • 26
  • 20
  • 12
    Its the `find_or_create_by_name( name )` style that is deprecated. `find_or_create_by( name: name )` is still fine and the recommended way of doing it, as per the documentation you link to... – Jonas Schubert Erlandsson Dec 28 '14 at 19:35