Rails find_or_initialize on relationship

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 the corresponding company, how can I avoid duplicates in companies?

Can I do something like:

 find_or_initialize_by_email_and_by_company_name(the_email, the_company_name) 

Thanks!

+4
source share
2 answers

Rails 3.2 way

 User.where(email: the_email, company_name: the_company_name).first_or_initialize 
+9
source

Using

 find_or_initialize_by_email_and_company_name(the_email, the_company_name) 

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

+2
source

Source: https://habr.com/ru/post/1435943/


All Articles