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
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
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.
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
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.