Skip to main content
if his suggestion made this answer better, even more reason to up vote your post :)
Source Link
OGHaza
  • 4.8k
  • 7
  • 26
  • 30

You could do this (but maybe ask yourself why):

user.attributes.key(user.first_name) 

...will return "first_name" as a String.

(Edited to reflect better answer by MrTheWalrus below. Please upvote his comment rather than this post).

You could do this (but maybe ask yourself why):

user.attributes.key(user.first_name) 

...will return "first_name" as a String.

(Edited to reflect better answer by MrTheWalrus below. Please upvote his comment rather than this post).

You could do this (but maybe ask yourself why):

user.attributes.key(user.first_name) 

...will return "first_name" as a String.

Better answer given by MrTheWalrus in comment below.
Source Link
Zach Kemp
  • 11.9k
  • 1
  • 35
  • 47

You could do this (but maybe ask yourself why):

user.attributes.select {|_,v| v == key(user.first_name }.keys.first) 

... which willwill return "first_name" as a String.

Are you looking for some way of determining which attribute matches a given input?

class User < ActiveRecord::Base #... def attribute_name_by_value(value) attributes.each {|k,v| return k if v == value } nil end end 

Then user.attribute_name_by_value("[email protected]") would return "email"(Edited to reflect better answer by MrTheWalrus below. Please upvote his comment rather than this post).

You could do this (but maybe ask yourself why):

user.attributes.select {|_,v| v == user.first_name }.keys.first 

... which will return "first_name" as a String.

Are you looking for some way of determining which attribute matches a given input?

class User < ActiveRecord::Base #... def attribute_name_by_value(value) attributes.each {|k,v| return k if v == value } nil end end 

Then user.attribute_name_by_value("[email protected]") would return "email".

You could do this (but maybe ask yourself why):

user.attributes.key(user.first_name) 

...will return "first_name" as a String.

(Edited to reflect better answer by MrTheWalrus below. Please upvote his comment rather than this post).

Source Link
Zach Kemp
  • 11.9k
  • 1
  • 35
  • 47

You could do this (but maybe ask yourself why):

user.attributes.select {|_,v| v == user.first_name }.keys.first 

... which will return "first_name" as a String.

Are you looking for some way of determining which attribute matches a given input?

class User < ActiveRecord::Base #... def attribute_name_by_value(value) attributes.each {|k,v| return k if v == value } nil end end 

Then user.attribute_name_by_value("[email protected]") would return "email".