Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a dynamic attribute

Is there a way to set col as dynamic or convert it in some way to a valid attribute? It is currently throwing the error: undefined method `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

Also, not sure if the title is accurate, please suggest if 'dynamic attribute' is the wrong term for this situation. Thanks

like image 587
iamtoc Avatar asked Mar 30 '12 00:03

iamtoc


2 Answers

I believe that you're looking for the following:

dest_table.send(:"#{col}=", xyz)
like image 130
Robin Avatar answered Oct 15 '22 01:10

Robin


You can try

dest_table.write_attribute(col, xyz)

OR

dest_table[col] = xyz

OR

dest_table.send("#{col}=", xyz)
like image 37
Harish Shetty Avatar answered Oct 15 '22 02:10

Harish Shetty