So I have a join table that relates to multiple models and stores the appropriate id and class like so:
Statistics
-----------------------------------
|object_type | object_id | value |
-----------------------------------
| "User" | 1 | 100 |
-----------------------------------
| "Post" | 61 | 50 |
-----------------------------------
I was hoping to use metaprogramming to do pass the “object_type” and somehow and use the resulting object like so:
send("User").find(1) #i.e. User.find(1)
send("Post").find(61) # Post.find(61)
Is there any good way to do this short of constructing a complicated if-else or case statement (i.e. if object_type == “User”…) ???
Classes are named with constants, so you can turn strings into classes easily with const_get:
or
But it’s generally better to use the first version as it’s closer to what you get when you refer to the class directly.