how to delete not saved data but i have assigned this data with build or new in rails?

275 views Asked by At

I have assigned record like this

profile_image = current_user.profile_images.build(params_profile_image)

But I don't want to save this record any more. Now how can I delete this profile_image unsaved record ?

1

There are 1 answers

0
Tommy On

For the variable profile_image, you don't need to do anything, it will be deleted once your code exit the block of where the variable is declared.

If you don't want to do anything else with current_user then you can just leave it too, and after the code exit the block where the variable is declared it will be gone, and next time you retrieve current_user it will be a new copy without the unsaved changes.

However if you want to continue using current_user you can do current_user.restore_attributes this will revert all unsaved changes to current_user. If you have other unsaved changes that you need to keep. I would recommend you to restructure the code to not call current_user.profile_images.build(params_profile_image) but rather Foo.build(params_profile_image) where Foo is the model class for profile_images. And only assign current_user.profile_images=profile_image once you're sure you need to save.