Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 517
Sylar Avatar asked May 16 '26 03:05

Sylar


1 Answers

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.

like image 190
Andrey Deineko Avatar answered May 18 '26 19:05

Andrey Deineko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!