Skip to content

Instantly share code, notes, and snippets.

@netzfisch
Created March 7, 2010 20:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save netzfisch/324613 to your computer and use it in GitHub Desktop.
Save netzfisch/324613 to your computer and use it in GitHub Desktop.
namespace :db do
desc "load data from csv"
task :load_csv_data => :environment do
require 'fastercsv'
FasterCSV.foreach("importdata/tarife.csv", :headers => true, :col_sep => ',') do |row|
Anbieter.find_or_create_by_name(
:name => row['Anbieter_Name']
:hotline => row['Hotline'],
:email => row['Email']
)
associated_anbieter = Anbieter.find_by_name(row['Anbieter_Name'])
associated_kategorie = Kategorie.find_by_name(row['Kategorie'])
associated_netz = Netz.find_by_name(row['Netz'])
Tarif.create(
:anbieter_id => associated_anbieter.id,
:kategorie_id => associated_kategorie.id,
:netz_id => associated_netz.id,
:name => row['Tarif_Name']
)
end
end
end
@tobyjoiner
Copy link

I am pretty new to rails still, but came across your code from a post on stack overflow.

Couldn't you just do (line 7):

associated_anbieter = Anbieter.find_or_create_by_name(
:name => row['Anbieter_Name']
:hotline => row['Hotline'],
:email => row['Email']
)

and skip the second lookup? or is that the right way to do it?

I am curious cause I am doing something very similar

(cant get the comment to look right, sorry)

@netzfisch
Copy link
Author

With

:name    => row['Anbieter_Name']
:hotline => row['Hotline'],
:email   => row['Email']

I just do mapping of different column names.

The rest of the code fills two tabels (Anbieter, Tarif) and get the right assoziation filled (anbieter_id)!

Does that help?

@tobyjoiner
Copy link

I am sorry. I was referring to the associated_anbieter part. Instead of doing

    Anbieter.find_or_create_by_name(
      :name    => row['Anbieter_Name']
      :hotline => row['Hotline'],
      :email   => row['Email']
    )

   associated_anbieter  = Anbieter.find_by_name(row['Anbieter_Name'])

couldn't you just do

   associated_anbieter  = Anbieter.find_or_create_by_name(
      :name    => row['Anbieter_Name']
      :hotline => row['Hotline'],
      :email   => row['Email']
    )

then you would save a database query. Or am I mistaken?

Thanks for this code, it has helped me a lot.

@netzfisch
Copy link
Author

I guess so, did you try it meanwhile, h-?

@tobyjoiner
Copy link

Yea I got it to work. Thanks again for the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment