2

I have an array of the desired columns to edit (wich is dynamic), like this:

toEdit = ["last_name_required", "email_required", "phone_required"]

Remember, it is dynamic so it can have only the phone. For example:

toEdit = ["phone_required"]

I have a Model with SQL Columns like:

last_name_required
email_required
phone_required

Those columns accept boolean values.

I want to generate a code to edit columns with the array values as parameters. Like this:

o = Model.fist
o.last_name_required = true
o.phone_required = true
o.save

I've tried something like:

o = Model.first
o.toEdit[0] = true
o.toEdit[1] = true
o.save

But I understand is wrong because I am trying to use a string as an object.

I don't know what's the appropriate syntax.

Any ideas?

Thanks

Emmanuel Orozco
  • 369
  • 1
  • 10

2 Answers2

6
o = Model.new
toEdit.each do |key|
  o.send "#{key}=".to_sym, true
end
o.save
GoGoCarl
  • 2,519
  • 13
  • 16
  • Brilliant. It's working. May I know why did you use the commas and then the .to_sym function? – Emmanuel Orozco Apr 14 '15 at 21:33
  • 1
    Be careful with this if `key` is from user input... http://stackoverflow.com/a/26284769/525478 – Brad Werth Apr 14 '15 at 21:46
  • @EmmanuelOrozco Sure; the comma since the call is actually `o.send("#{key.to_sym}=", true)`, so the first parameter is the symbol name of the function, and the second parameter is the value, in this case, `true`. Regarding, to_sym, it's just what's used by the method signature. Details: http://apidock.com/ruby/Object/send – GoGoCarl Apr 14 '15 at 22:17
  • @EmmanuelOrozco Actually thanks for pointing that out I noticed I left my answer a bit superfluous. You can use EITHER to_sym or string, but certainly both are not required (although, as you see, it works). The updated answer can be used either with or without the to_sym. I always use to_sym just because I always have (and the docs say so), but it doesn't seem to be required. Also, I would emphasize what @Brad said, make sure you control what goes in that array, otherwise something like `['phone_required', 'destroy']` could be harmful – GoGoCarl Apr 14 '15 at 22:23
  • to_sym is not really needed here – Mayuresh Srivastava Jul 29 '22 at 11:23
2

You can try below code.

toEdit = ["last_name_required", "email_required", "phone_required"]
object = Model.new
object.columns.map(&:name).each do |column_name|
    object.column_name = true if  (toEdit.includes? column_name)
end
Jagdish
  • 752
  • 8
  • 23