0

I have such situation: I have Users table and I divide users by type: Admins, Managers, Customer.

Managers can be created only with Organizer model( organizer has_many managers) and it is creating on nested form.

I want to upgrade Customer to Manager if someone is trying to create Manager with already registered Customer's email.

Current situation:

When I'm trying to create Manager with Customer's email it showing me database error. I can make some validation to change Customer type -> to -> Manager, but it still wants to save Manager record and obviously failing and giving me next error.

   ActiveRecord::RecordNotUnique:
   PG::Error: ERROR:  duplicate key value violates unique constraint "index_users_on_email"

How I can handle this RIGHT ?

P.S. Here is my models code:

 class Organizer
 accepts_nested_attributes_for :managers
 has_many :managers
 ___________________

 class Manager < User
 belongs_to :organizer

 ___________________

 class Customer < User
Denys Medynskyi
  • 2,353
  • 8
  • 39
  • 70

1 Answers1

0

You should first check if such a record with specified email ID exists in your Users table.

  • If yes, update the role col in that record to Manager,
  • else insert a new record.
Pradeep Pati
  • 5,779
  • 3
  • 29
  • 43
  • it easy to say) I need to validate manager's email very time it is changing or creating, so how I could skip saving if this email is already taken ? – Denys Medynskyi Apr 03 '13 at 13:27
  • select count(rowid) from Users where where email=';' If it returns greater than 0, you already have the user. – Pradeep Pati Apr 03 '13 at 13:37
  • I can find customer with this ecode: `Customer.find_by_email(self.email)` but how I can skip saving record ? And how I can do skipping record saving ? It seems, that you don't undersand problem. I will write more in question. – Denys Medynskyi Apr 03 '13 at 13:41
  • using if/else conditionals... if(customer exists) update role else insert customer – Pradeep Pati Apr 03 '13 at 13:42
  • Where I should put if statements ? In validation or some callback ? – Denys Medynskyi Apr 03 '13 at 13:46