0

What's the best approach to import multiple lines from a text_area in a form?

I've tried a quick bodge using FasterCSV but get a NoMethodError:

undefined method `pos' for {"name"=>"Carrots\r\nPeas\r\nRed Onion"}*
  def create
    FasterCSV.parse(params[:ingredient], {:headers => false, :quote_char => '"', :col_sep => ','}).each do |row_data|
          new_record = Ingredient.new('name' => row_data[0])
          new_record.save
      end

I want to apply the final thing to a model with multiple columns hence the col_sep

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Raoot
  • 1,751
  • 1
  • 25
  • 51

1 Answers1

1

If you want to use FasterCSV.parse on single lines, you need to get simple lines first.

Split the multi-line data first:

params[:ingredient][:name].split.each do |line|
  FasterCSV.parse(line, { ... options ... }).each do |row_data|
    ... etc ...

I might use parse_line to explicitly communicate I'm working on a single line instead.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • I don't necessarily want to use FasterCSV. I've just used it successfully to import CSVs previously and thought the process would be similar. I've tried what you suggested but get `private method `split' called for` as an error. – Raoot Jun 18 '12 at 10:22
  • That's not a helpful error message. The point is that you need to split the incoming string parameter into individual lines if you want to use the line-parsing methods of FasterCSV--you made the same mistake in your original code; if `ingredient` is a model, then you need to access a specific model field. Updated example. Although "name" is a weird attribute name for something other than a name. – Dave Newton Jun 18 '12 at 10:30
  • This is only a dummy app to try and get the approach right. I'll use better attribute names in the real thing. This seems to be kind of working, now getting a undefined method `save' for nil:NilClass error, but the values are added to the db. Also if I enter 'Chick Peas' for example, I get two entries. On the right path though, thanks for your help. – Raoot Jun 18 '12 at 11:01
  • @RyanBerry You should split on newlines then. Don't just type in code, look stuff up. – Dave Newton Jun 18 '12 at 11:02
  • Haha, I generally do but find trial and error or learn by mistakes also works now and again. Kind of under pressure to do a quick fix with this hence trying to hack it out blindly. Thanks again. – Raoot Jun 18 '12 at 11:10