DanTdd
DanTdd

Reputation: 342

Iterating through multiple fields on form post data

In my rails app, I currently am able to get form post data from a two form fields of name="start" and name="end". The post data is as follows:

start: 2018-05-18 12:00
end: 2018-05-18 12:00

Here is the code that takes the post data and does something with it.

post "/time" do
  time = DoTime.new
  start = params["start"]
  finish = params["end"]
  time.started_at = start
  time.finished_at = finish
  time.profile = current_user
  time.save
  redirect "/profile"
end

I have since implemented a dynamic form which allows the user to duplicate the start and end fields as many times as they want. All this does is add the HTML form fields in place before submission and posts it with the form. An example of the new post data is here:

start: 2018-05-18 12:00
end: 2018-05-18 12:00
start: 2018-05-19 12:00
end: 2018-05-19 12:00

I am wondering how I can loop through the ruby to look for each instance of start and end and run the code above for each of the elements it finds. Any pointers or advice? I have tried a few different ways but keep running into errors.

Thanks

Upvotes: 0

Views: 83

Answers (1)

Lymuel
Lymuel

Reputation: 58

If I understand your question correctly, you expect params[:start] and params[:end] to contain an array of dates. To be able to do that, you need to set the name attribute of all duplicate start fields to "start[]" and similarly for end fields, set it to "end[]".

Now, you can iterate on the values in your controller and create multiple objects as follows:

post "/time" do
  # Assuming the number of starts and ends will be same, ...
  params[:start].count.times do |i|
    time = DoTime.new
    time.started_at = params[:start][i]
    time.finished_at = params[:end][i]
    time.profile = current_user
    time.save!
  end

  redirect "/profile"
end

Upvotes: 2

Related Questions