variables - Rails 4 CSV Import and setting a value to a key value -


i'm complete rails n00b , i'm sure easy thing i'm having trouble. take value of key in url , set :category_id of record in database import record csv.

i can work creating category_id field in csv file , using following code import file

  def self.import(file)     csv.foreach(file.path, headers: true) |row|       record = manufacturer.where(:category_id => row[1], :name => row[0] ).first_or_create       record.save!     end   end 

but requires adding category_id csv.. like

def self.import(file)   csv.foreach(file.path, headers: true) |row|     record = manufacturer.where(:category_id => @category, :name => row[0] ).first_or_create     record.save!   end end 

where @category set in url. like: ...localhost:3000/manufacturers/import_manufacturer/2?category_id=2 saves record sets category id "null" - server output:

started post "/manufacturers/import?category_id=2" 127.0.0.1 @ 2013-07-18 11:19:55 +0200 processing manufacturerscontroller#import html parameters: {"utf8"=>"✓", "authenticity_token"=>"duaw1ponajiebyn7qeqgortymc74otlt6tt/e1dkaiu=", "file"=>#<actiondispatch::http::uploadedfile:0x007f835e3cae40 @tempfile=#<file:/var/folders/9j/4hs3_7kx11x3h4gkcrrgkwhc0000gq/t/rackmultipart20130718-23913-k0z3a8>, @original_filename="citroen.csv", @content_type="text/csv", @headers="content-disposition: form-data; name=\"file\"; filename=\"citroen.csv\"\r\ncontent-type: text/csv\r\n">, "commit"=>"import", "category_id"=>"2"} category load (0.3ms)  select `categories`.* `categories` `categories`.`id` = 2 limit 1 manufacturer load (0.6ms)  select `manufacturers`.* `manufacturers` `manufacturers`.`category_id` null , `manufacturers`.`name` = 'citroen' order `manufacturers`.`id` asc limit 1  (0.3ms)  begin sql (0.5ms)  insert `manufacturers` (`created_at`, `name`, `updated_at`) values ('2013-07-18 09:19:55', 'citroen', '2013-07-18 09:19:55') (0.5ms)  commit (0.2ms)  begin (0.1ms)  commit manufacturer load (0.6ms)  select `manufacturers`.* `manufacturers` `manufacturers`.`category_id` null , `manufacturers`.`name` = 'citroen' order `manufacturers`.`id` asc limit 1 (0.2ms)  begin (0.1ms)  commit 

is possible pass variable csv.foreach loop this?

thanks in advance , sorry if i'm asking stupid question.

if class method import called in import controller action, can pass params[:category_id] 2nd parameter.

class manufacturerscontroller < applicationcontroller   def import     manufacturer.import(params[:file], params[:category_id])   end end  class manufacturer < activerecord::base   def self.import(file, category_id)     csv.foreach(file.path, headers: true) |row|       record = manufacturer.where(         :category_id => category_id,         :name => row[0]       ).first_or_create     end   end end 

Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -