Sylar Sylar - 1 month ago 12
Ruby Question

Get attribute's name by it's value

I need to return the key with a known

value
from my model.

f = Foo.find_by(name: "dave", age: 32)
f.key("dave") # expected :name or name


This
value
will be unique. How to get the attribute? Am I asking the right question?

What is the difference with this, please?

hash = { "a" => 100, "b" => 200, "c" => 300, "d" => 300 }
hash.key(200) #=> "b"

Answer

f is an instance of Foo class, which inherits from ActiveRecord::Base, it is not a Hash instance.

To get the attribute's name by it's value (using key), you have to get a hash of f's ActiveRecord::AttributeMethods#attributes first:

f.attributes.key('dave') # `attributes` method returns a Hash instance
#=> "name"

What is the difference

To sum up: the difference in the instance methods defined in the object's class.