Dynamically get Object's attribute

后端 未结 3 1951
失恋的感觉
失恋的感觉 2021-02-07 13:09

How do I dynamiclly get an attribute value for an activerecord object?

for example I have a variable named attr_name.
I want to do something like this

相关标签:
3条回答
  • 2021-02-07 13:48

    send is the method you're looking for.

    0 讨论(0)
  • 2021-02-07 13:57

    If doing this using send

    address = person.send("function_name" + "attr_name")
    
    0 讨论(0)
  • 2021-02-07 14:07

    Either use person.attributes[attr_name] or person.read_attribute(att_name), or even shorter then this is person[attr_name].

    0 讨论(0)
提交回复
热议问题