Ask A Question

Notifications

You’re not receiving notifications from this thread.

CSV Import

Sascha M. asked in Ruby

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!

Reply
  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
Reply

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 ?

Reply

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.

Reply
Join the discussion
Create an account Log in

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

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

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

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.