10

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

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
iamtoc
  • 1,569
  • 4
  • 17
  • 24

3 Answers3

16

I believe that you're looking for the following:

dest_table.send(:"#{col}=", xyz)
Robin
  • 21,667
  • 10
  • 62
  • 85
13

You can try

dest_table.write_attribute(col, xyz)

OR

dest_table[col] = xyz

OR

dest_table.send("#{col}=", xyz)
lulalala
  • 17,572
  • 15
  • 110
  • 169
Harish Shetty
  • 64,083
  • 21
  • 152
  • 198
0

Perhaps a more idiomatic Rails solution would be to use

assign_attributes or attributes=(which is an alias of assign_attributes).

attrs = User.column_names.each_with_object({}) do |col, hash|
  hash[col] = xyz
end

dest_table.assign_attributes attrs

Also, related question:

Rails update_attributes without save?

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91