How can I use a variable to access the fieldname of a ruby object in erb? ex. Model.task_#{variable}

StackOverflow https://stackoverflow.com/questions/1460831

  •  13-09-2019
  •  | 
  •  

Question

I have a to-do list with 5 tasks that are stored on the same record.

Todo.task_one, Todo.task_two, etc.

What I would like to do is be able to loop through the fields like this

total_tasks = ["one", "two", "three", "four", "five"]
for tasks in total_tasks
Todo.task_#{tasks} = "text here"
end

However, this doesn't work unless I use eval "Todo.task_#{tasks} = 'text here'" which I know isn't safe. Even using eval isn't really the solution, because I need to do this in the view using erb, so I'm kind of stuck.

Was it helpful?

Solution

Ruby is full of metaprogramming utilities. One such utility is Object#send.

["one", "two", "three", "four", "five"].each do |task|
  Task.send("task_#{task}=", "text here")
end

Another option is to not give the tasks human friendly method names.

5.times do |i|
  Task.tasks[i] = "foo"
end

OTHER TIPS

What you're looking for is the send method that all Ruby objects have. It allows you to 'send' a message (which is what calling a method really is anyways) with a string.

Example:

Todo.send("task_#{tasks}")

It will return whatever your task methods return.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top