0

so I have a textfield, where a user can put comma seperated card IDs, for example 1,2,3. When this user submits the form, I want to create a new record of each ID he submits. So one for 1, one for 2, one for 3.

How would I do that?

Thank you

pgrosslicht
  • 1,552
  • 13
  • 18
  • You also may use bulk insert, please, see [this question][1] [1]: http://stackoverflow.com/questions/8505263/how-to-implement-bulk-insert-in-rails-3 – Arthur Jul 27 '12 at 17:49

3 Answers3

0

Try

ModelName.create(input_string.split(',').map{ |i| { :field => i.strip } })

split will split input on comma and map will generate an array of { :field => i } where :field is your model's textfield.

Kulbir Saini
  • 3,926
  • 1
  • 26
  • 34
0

You must parse input value from textfield in your controller. For example:

def update
   ids_input=params[:ids]
   ids_input.split(',').each { |id|
      Card.create(:some_id=>id,:other_column=>'some_value',:related_user=>current_user)
   }
end
rogal111
  • 5,874
  • 2
  • 27
  • 33
0

There are several ways to accomplish that, depending on your specific needs. One way would be to loop through all the entries in your controller, like @rogal111 is suggesting in his answer.

If you have a one-to-many relationship between your User and the Cards, which is most probably the way to go anyway, I would suggest that you accomplish it through a nested form. Ryan Bates has done some excellent screencasts on that one.

klaffenboeck
  • 6,297
  • 3
  • 23
  • 33