Delete an element in a hash without deleting the model

I want to delete an element from a hash in Rails. The delete method looks promising, and works well with one unintended consequence... it deletes the model.

# Get all users.
@search = User.all

# Unset yourself. Your ID is stored in current_user.id
@users.delete(current_user.id)

The resulting @users hash does in fact have your own ID removed... but it also deletes the model. What is the correct way to simply unset that key in Ruby / Rails?

Answers


The behaviour you describe isn't accurate on many counts. First, User.all returns an array, not a hash, so assuming you're using ActiveRecord here, the premise of your question is flawed.

Secondly, deleting an item from an array using Array#delete will definitely not invoke delete on the item itself. That just isn't true. It wouldn't do so for a hash either.

Thirdly, it also won't delete the item from the array at all, unless its index happens to match the index of the item in the array, which isn't very likely. You're wildly misinterpreting you experiment.

You don't delete things from an array by passing some field belonging to the object (like ID) to Array#delete. You need to pass the array index. You would need to figure out the index of the record matching your current user, and pass that into delete.

However, if you want to remove an object from array by one of its properties, using reject is much better:

@users.reject! { |u| u.id == current_user.id }

Need Your Help

How to make faster pushing a UIViewController into a UINavigationController

iphone uiviewcontroller uinavigationcontroller uitextfield freeze

I have a multiple view based application, the problem is that when I push one UIViewController the device (only when I test it on a real device) freezes for a second or two, I don't know why is this

Text is not getting Highlighted in Combobox when selectedindex changed through code

c# .net controls combobox

I am using combobox which contains three value-NSW,TIC,VIA. in page load i m setting selectedindex = 1 for the combobx , the value shown as TIC which is correct but it is not getting highlighted. I...