【问题标题】:How to set a dynamic attribute如何设置动态属性
【发布时间】:2012-03-30 00:26:03
【问题描述】:

有没有办法将 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

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

【问题讨论】:

    标签: ruby-on-rails ruby dynamic-attributes


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你可以试试

      dest_table.write_attribute(col, xyz)
      

      dest_table[col] = xyz
      

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

      【讨论】:

      • write_attribute 是私有方法