Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 find or create by method doesn't work

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 
like image 932
Loenvpy Avatar asked Mar 19 '14 23:03

Loenvpy


2 Answers

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 
like image 50
eronisko Avatar answered Oct 05 '22 05:10

eronisko


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 
like image 34
Kalpesh Fulpagare Avatar answered Oct 05 '22 04:10

Kalpesh Fulpagare