通过它的值获取属性的名称
Get attribute's name by it's value
我需要 return 具有我模型中已知 value
的密钥。
f = Foo.find_by(name: "dave")
#= returned object: {id: 1, name: "dave", age: 32}
f.key("dave") # expected :name or name
这个 value
将是独一无二的。如何获得属性?我问的问题对吗?
请问这有什么区别?
hash = { "a" => 100, "b" => 200, "c" => 300, "d" => 300 }
hash.key(200) #=> "b"
f
是Foo
class的一个实例,继承自ActiveRecord::Base
,不是Hash
实例。
要通过值获取属性名称(使用 key
),您必须先获取 f
的 ActiveRecord::AttributeMethods#attributes
的哈希:
f.attributes.key('dave') # `attributes` method returns a Hash instance
#=> "name"
What is the difference
总结一下:对象class.
中定义的实例方法的区别
我需要 return 具有我模型中已知 value
的密钥。
f = Foo.find_by(name: "dave")
#= returned object: {id: 1, name: "dave", age: 32}
f.key("dave") # expected :name or name
这个 value
将是独一无二的。如何获得属性?我问的问题对吗?
请问这有什么区别?
hash = { "a" => 100, "b" => 200, "c" => 300, "d" => 300 }
hash.key(200) #=> "b"
f
是Foo
class的一个实例,继承自ActiveRecord::Base
,不是Hash
实例。
要通过值获取属性名称(使用 key
),您必须先获取 f
的 ActiveRecord::AttributeMethods#attributes
的哈希:
f.attributes.key('dave') # `attributes` method returns a Hash instance
#=> "name"
What is the difference
总结一下:对象class.
中定义的实例方法的区别