Alon Shmiel
Alon Shmiel

Reputation: 7121

Remove a row from a table to another table

I have two tables: Admin and Worker. they have the same arguments (email, password, etc).

I tried to remove the row that contains the email: "[email protected]" from Worker table into the Admin table (and delete it from the Worker Table).

I tried the next thing:

@email = '[email protected]'
@row_email_deleted = Worker.find_by_email(@email)
Admin.add(@row_email_deleted)
@row_email_deleted.destroy

but it doesn't work :/

Can someone help me to fix my problem?

Upvotes: 0

Views: 117

Answers (2)

Tolik Kukul
Tolik Kukul

Reputation: 2016

Try this:

@email = '[email protected]'
@worker = Worker.find_by_email(@email)
@new_admin = @worker.becomes Admin
@new_admin.save
@worker.destroy

But I propose you should try to refactor to STI e.g.: http://blog.thirst.co/post/14885390861/rails-single-table-inheritance

Upvotes: 2

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

Along with apneadiving, I don't know what the 'add' method is composed of. That and not a lot of detail on exactly what isn't working makes it hard to know why it's not working. That said, ignoring all of that, I would do something like this:

Worker.transaction do
  @email = '[email protected]'
  @worker = Worker.find_by_email(@email)
  Admin.create(@worker.attributes.reject{|k,v| %w[id].include?(k)}) 
  @worker.destroy
end

Upvotes: 1

Related Questions