2011-06-29 62 views
0

我有一個字符串數組:[「users」,「torrents」,「comments」] 這些字符串是我的bd表的名稱。在Ruby On Rails中進行元編程

我該如何在.each循環連接到這些表並選擇一些數據?

回答

6

避免使用eval

這裏是用一個簡單的解決方案constantize

注:constantize將不允許進行評估,它只是嘗試任意代碼獲取紅寶石不變,即Class

["users", "torrents", "comments"].each do |table_name| 
    # "users" => "User" 
    # or more complex 
    # "some_models" => "SomeModel" 
    # 
    class_name = table_name.singularize.camelize 

    # "User" => User 
    model_class = class_name.constantize 

    # do something with it 
    model_class.create!(:value => 12345) 
end