Spliting up text in a text_area_tag

I am tryinng to create a text area box where you can enter in the part number and quantity into it and I then want it adding to the cart.

So in the text area field I want it so you would do this.

10-10-10, 12
12-13-14, 4

When I look at the params in the log it comes up as :template1 => "10-10-10, 2\r\n\11-12-13,4"

My thoughts on how to do this was to split up the string so i manged to somehow get the product and quantity based on the \r\n using split and then pass it into FastOrderLines.create to add it to my cart.

I am struggling to split the string up into something workable, any help or advice will be much appreciated.


Does params[:template1].split(/[\r\n]+/) work?

Not to derail the conversation, but from a UX perspective, couldn’t using a text area box create a lot of opportunities for human errors when entering the data? For example if I put in 20 parts and quantities but make a typo on part 17, it would be hard to give specific feedback on any error that might happen.

It seems to me you might want to have individual fields for the part number and the quantity, so if the person happens to put ‘whoopsie daises’ for a part number you could return the form and say ‘Fix it!’.

Admittedly, I don’t know the entire context of your form, so it might be a terrible idea for your application, but just something to think about nonetheless.

Good point @dolphorama, there’s a railscast covering how to make nested forms which could be helpful.

Thanks for all your help and comments guys,

This is what I came up with in the end:

lines = params[:template1].lines

    orders = lines.map do |line|
      x = line.chomp.split(",")
      part_no, qty, type, a, b, date, time, ref = x
        entered_prnum: part_no.split("/").last,
        qty: qty,
        vat_rate: Cart.default_vat_rate,
        line_vat: 0,
        product_id: 0,
        price: 0.0,
        selling_unit: 1,
        special_id: 0,
        user_id: self.current_user.id,
        checkoutref1: a,
        checkoutref2: b,
        checkoutref3: ref

The user just pastes this already formated in the way it’s needed, and it does get validated before it adds to the cart, it is already using nested_attributes_for but thanks for suggesting that, this is for a faster entry.