Skip to main content

CSV Import

Ruby • Asked by Sascha M.

My question is about this Episode: https://gorails.com/episodes/upload-csv-form

The CSV Import works fine (I'm using the exact same code actually).

My 1. Question - How can I define an alias for my rows?

This is the code:

def self.assign_from_row(row)
order = Order.where(token: row[:token]).first_or_initialize
order.assign_attributes row.to_hash.slice(:token, :order_id, :customer_id)
order
end

How would you implement aliases for token (utm_campaign) order_id (ordernumber) and customer_id (customer)? It's annoying to change the row names each time.

My 2. Question - Accept Semicolons as a Divider

In Germany it is common to use a ";" as a divider inside a .csv. US Standard is a comma. What should be edited so both is possible?

Many Thanks in Advance!


  1. You'll probably need to modify that hash of attributes from the row. For example, you could transform it this way:
# Accept all fields you could ever want
attrs = row.to_hash.slice(:token, :order_id, :customer_id, :utm_campaign, :ordernumber, :customer)

# Set aliases
attrs.merge(
  token: attrs.delete(:utm_campaign),
  order_id: attrs.delete(:ordernumber),
  customer_id: attrs.delete(:customer)
)
order.assign_attributes(attrs)
  1. The col_sep option is what's used to define the column separators. You can add col_sep: ";" into your CSV parser section and that should do it. Some more info here on options: http://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html

Great. Thank you for your detailed answer! I Just saw, that "order_id" actually is named "reference code" with a space. How do I need to write it :ReferenceCode, or :reference_code ?


You'll actually want to just make sure it matches the column name I think. You can print out the row hash to the console to see exactly what you'll need for that.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.