2012-03-30 118 views
5

有沒有辦法將col設置爲動態或將其以某種方式轉換爲有效屬性? 這是目前引發錯誤:未定義的方法`山坳=」#爲...如何設置動態屬性

def copy_stock_data_from_sandbox(cntrlr) 
    source_table = cntrlr.singularize.classify.constantize 
    dest_table = source_table.new 
    source_table.column_names.each do |col| 
    dest_table.col = xyz # <------ This is the line in question 
    end 
    dest_table.save 
end 

而且,不知道標題是準確的,請建議,如果‘動態屬性’是造成這種情況的錯誤術語。由於

回答

11

我相信你正在尋找如下:

dest_table.send(:"#{col}=", xyz) 
7

您可以嘗試

dest_table.write_attribute(col, xyz) 

OR

dest_table[col] = xyz 

OR

dest_table.send("#{col}=", xyz) 
+0

'write_attribute'是一個私有方法 – 2017-08-08 11:25:06