Friday, 15 July 2011

Importing associated models from single csv in rails 3 -



Importing associated models from single csv in rails 3 -

i've been next rails cast episode, importing csv , excel, have different setup.

i have 2 models, usage(amount) & price(amount). have set usage has_one cost , cost belongs_to usage. in csv, have 2 columns, so:

usage,price 1000,0.1 1500,0.11

i'm trying import info can usage.amount & usage.price.amount database.

i had here, , tried there. 1 thing note don't have id column (although tried id column , code question still didn't work).

here code model:

class usage < activerecord::base has_one :price, dependent: :destroy accepts_nested_attributes_for :price def self.import(file) csv.foreach(file.path, headers: true) |row| usage.create! row.to_hash end end end

note: know above has no reference importing price.amount, tried wouldn't work.

any help on appreciated, thanks!

update

here's how got working: (thanks alalani helping next code.)

csv.foreach(file.path, headers: true) |row| u = usage.create(amount: row[0]) u.create_price(amount: row[1]) end

why don't create new instances of class , add together manually?

so do:

def self.import(file) csv.foreach(file.path, headers: true) |row| u = usage.new(:amount => row[0]) u.save p = price.new(:amount => row[1]) p.save u.price << p end end

it seems little bit more work, simple understand whats going on here

ruby-on-rails ruby-on-rails-3 csv import

No comments:

Post a Comment