Rails referencing parent id during csv import -


firstly, i'm sorry ask such basic question i'm new rails, ruby & development in general , lack of terminology understanding means having hard time finding answer question.

i importing csv of vehicle data using:

def self.import(file, category_id) csv.foreach(file.path, headers: true) |row|   model.where(   :category_id => category_id,    :name => row[1],   :cap_id => row[10]    ).first_or_create |record|     record.layout = row[3], 

... several records later ...

    record.manufacturer_id = manufacturer.where(:name => row[0], :category_id => category_id).id   end end end 

but having trouble setting manufacturer_id last line of loop. guess can see i'm trying here can't work out how should written.

basically have list of manufacturers belonging different categories (so, example, there ford manufacturer category_id=1 (for cars) , ford manufacturer category_id=54 trucks.

can set manufacturer_id of each record taking current category_id , manufacturer name csv, cross referencing them , pulling id of result?

when trying above code following error:

nomethoderror in modelscontroller#import undefined method `id' #<activerecord::relation::activerecord_relation_manufacturer:0x007fcd96f744a8> extracted source (around line #33):  32      record.description = row[2], 33      record.manufacturer_id = manufacturer.where(:name => row[0], :category_id => category_id).id 34    end 35    end 36  end 

the following line of code returns activerecord::relation object

manufacturer.where(:name => row[0], :category_id => category_id) 

so when called id on it, raised error. should call first first , id.

manufacturer.where(:name => row[0], :category_id => category_id).first.id 

be warned doing assumes you'll manufacturer matches condition. more safe, can use try

manufacturer.where(:name => row[0], :category_id => category_id).first.try(:id) 

Comments