ruby on rails - Is there way to call a table as a variable in Active Record? -


the title bit confusing, let me explain.

i have 3 model classes called table1, table2, , table3. 3 tables have "total" column.

this want able do:

index = either 0, 1, or 2 tablenames = ["table1", "table2", "table3"] tablenames[index].total 

^ can't because tablenames[index] returns string, not reference actual class itself.

this i'm doing:

index = either 0, 1, or 2 if index == 0     table1.total elsif index == 1     table2.total elsif index == 2     table3.total end 

i guess want bit analogous "send" method in ruby, can use variables method names.

is there way this, or have if elsif check? makes code longer , clunkier , i'm wondering if there's better way. thanks!

if getting model name string. can this

 model_name = "table1" #or "table2", "table3" model = model_name.constantize  model.total 

you can directly turn string class constantize method.

note - if going use rails further, ideally refer them models not tables.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -