Sylar
Sylar

Reputation: 12092

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")
#= returned object: {id: 1, 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"

Upvotes: 3

Views: 1682

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52377

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.

Upvotes: 5

Related Questions