8

有没有办法将col设置为动态或以某种方式将其转换为有效属性?它目前正在抛出错误:未定义的方法 `col=' for #...

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

另外,不确定标题是否准确,请指出“动态属性”是否是这种情况的错误术语。谢谢

4

2 回答 2

15

我相信您正在寻找以下内容:

dest_table.send(:"#{col}=", xyz)
于 2012-03-30T00:34:39.440 回答
12

你可以试试

dest_table.write_attribute(col, xyz)

或者

dest_table[col] = xyz

或者

dest_table.send("#{col}=", xyz)
于 2012-03-30T00:39:32.267 回答