Ask A Question


You’re not receiving notifications from this thread.

CSV Import

Sascha M. asked in Ruby

My question is about this Episode:

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)

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
  token: attrs.delete(:utm_campaign),
  order_id: attrs.delete(:ordernumber),
  customer_id: attrs.delete(:customer)
  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:

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.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 83,453+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.