通过属性的值获取属性的名称

时间:2021-02-20 20:32:20

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"

1 个解决方案

#1


4  

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

f是Foo类的一个实例,它继承自ActiveRecord: Base,它不是一个哈希实例。

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的ActiveRecord::AttributeMethods#属性的散列:

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.

总结:对象类中定义的实例方法的差异。

#1


4  

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

f是Foo类的一个实例,它继承自ActiveRecord: Base,它不是一个哈希实例。

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的ActiveRecord::AttributeMethods#属性的散列:

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.

总结:对象类中定义的实例方法的差异。