Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash.except() doesn't work with symbol keys

I have a piece of code where this line:

user.attributes.except('created_at', 'created_by', 'updated_at', 'updated_by', 'id')

works (returns the hash with the keys passed as arguments removed from it), whereas changing it to:

user.attributes.except(:created_at, :created_by, :updated_at, :updated_by, :id)

doesn't (the returned hash still contains all the keys). How is this possible?

like image 608
bluehallu Avatar asked Dec 07 '22 12:12

bluehallu


2 Answers

Because attributes returns a Hash with keys as string and not symbol.

http://apidock.com/rails/ActiveRecord/Base/attributes

and as said by others, String != Symbol.

puts :a == 'a'
# => false
like image 125
oldergod Avatar answered Dec 17 '22 15:12

oldergod


This happens because the keys in user.attributes are strings. You can symbolize them using symbolize_keys method and then use except with symbols like this.

user.attributes.symbolize_keys.except(:created_at, :created_by, :updated_at, :updated_by, :id)
like image 21
Kulbir Saini Avatar answered Dec 17 '22 13:12

Kulbir Saini