Posh344
Posh344

Reputation: 43

Get a value of an attribute in ActiveRecord

Here's my code:

a1.superclass
=> ApplicationRecord(abstract)

Also I have the name of an attribute as a string. How can I get its value? This doesn't work:

a1.send(attr1)
a1[attr1]

This does, but it returns Hash:

 a1.attribute(attr1)


=> {"my_super_attr"=>[#<ActiveModel::Type::Value:0x0055b83c524ac8 @precision=nil, @scale=nil, @limit=nil>, {}]}

How can I retrieve the actual value?

Upvotes: 0

Views: 59

Answers (1)

Clemens Kofler
Clemens Kofler

Reputation: 1968

If a1.superclass returns ApplicationRecord(abstract), this means that a1 is a class and not an actual record. You can't read a value from a class since it's not an instance. If you do something like a1.first[attr1], everything should work just fine.

Upvotes: 2

Related Questions