Activerecord send to belongs_to relationship

Hi folks, I’m parameterizing a bunch of lookups in a model, and I’m running into a limitation to activerecord’s send method. Account and Person are two models with a belongs_to/has_many relationship.

record = AccountGroup.first

puts record.ugid

puts record.send(‘ugid’)

puts record.person.firstname

puts record.send(‘person.firstname’)

The first three lookups work, but the last one fails with a ‘method missing’ error. Of course “puts record.send(‘person’).send(‘first’)” works, but I can’t parameterize that form.

Anyone have any suggestions for this? eval is always an option, but I’d like to avoid it if possible. Thanks much!


Have you tried something like this:

keys = "person.firstname"
keys.split(".").reduce(record) { |value, key| value.send(key) }

Although you should be careful because with the origin of those keys.

Benito, that’s genius. I hadn’t thought of using reduce for this. Thanks!