Reputation: 7121
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
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
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
Wrap the whole thing in a transaction to ensure that you you don't delete the worker but not add the admin. http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html
The 'reject...' bit is to remove any worker attributes that you don't want in Admin (or that can't be passed en-masse).
Upvotes: 1