2012-03-08 193 views
0

我正在寫一個rails函數,它可以將Car或Building對象添加到City對象。使用字符串輸入引用方法或屬性

該功能的第一部分是創建具有給定名稱的汽車或建築物對象,然後將其附加到城市的汽車或建築物列表中。

def addObject(obj_type,obj_name,city_id) 
    new_obj = obj_type.constantize.create(:name => obj_name) 
    city = City.find(city_id) 

    city.obj_type.underscore.pluralize << new_obj 
end 

隨着Inflector,程序可以使用constantize引用期望的模型類。

(感謝Referencing Model with String input

如:

new_obj = obj_type.constantize.create(:name => obj_name) 

但是,試圖訪問City物體內部的名單,

obj_type.underscore.pluralize 

可以把 「汽車」 到「汽車時, 「

然而,它只會像第E按照行不通:

city.obj_type.underscore.pluralize #city.cars desired 

將某種類型的元編程功能,如eval()需要?

謝謝你在前進,

+1

你見過'變形器#tableize'? – Eric 2012-03-08 08:59:11

+0

似乎與'Inflector#underscore'和'Inf​​lector#pluralize'一起做同樣的事情。感謝您指出它! – rickypai 2012-03-08 10:15:08

回答

2

你可以這樣做:

city.send(obj_type.underscore.pluralize) << new_obj 

在這種情況下,你創建你想叫你的城市客體和發送使用它的方法

+0

謝謝。這完美的作品! – rickypai 2012-03-08 08:41:18

相關問題