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?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With