Ain Tohvri
Ain Tohvri

Reputation: 3035

CSV upload parsing in Rails

Could someone advise with the following CSV parsing issue:

CSV:

Robert,Lobos,[email protected]
Klein,Kleinerer,[email protected]
Gross,Grosserer,[email protected]

Method:

def upload
  if (params[:contactList])

    csv_content = params[:contactList].read
    @recipients = {}
    CSV.parse(csv_content) do |row|
      @recipients[row[0]] = {'forename' => row[0], 'surname' => row[1], 'email' => row[2]}
    end

    render 'index'
  end
end

Target is to render the values in the template as following:

<% @recipients.each do |recipient| %>
  <option value="test"><%= recipient['forename'] %> <%= recipient['surname'] %> (<%= recipient['email'] %>)</option>
<% end %>

Currently throws up with:

can't convert String into Integer

What's the best way/quickfix to achieve the above?

Upvotes: 0

Views: 93

Answers (1)

deefour
deefour

Reputation: 35370

To iterate a hash with a block, the key and value of the hash entries are provided to the block.

<% @recipients.each do |recipient| %>

should be

<% @recipients.each do |key, recipient| %>

Upvotes: 1

Related Questions