Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails find_or_initialize on relationships

when I create a new user, to avoid duplicates, I use the find_or_initialize method:

user = find_or_initialize_by_email(the_email)

If this user is created with a related company, how can I avoid the duplicates in companies?

Can I do something like:

find_or_initialize_by_email_and_by_company_name(the_email, the_company_name)

Thanks!

like image 406
ndemoreau Avatar asked Dec 15 '22 19:12

ndemoreau


2 Answers

Rails 3.2 way is

User.where(email: the_email, company_name: the_company_name).first_or_initialize
like image 150
Amit Patel Avatar answered Jan 04 '23 16:01

Amit Patel


Using

find_or_initialize_by_email_and_company_name(the_email, the_company_name)

you will create users uniq both by email and company name. (by is used only once)

like image 24
Aleks Avatar answered Jan 04 '23 17:01

Aleks