Rails 4 CSV Import and setting a value to a key va

2019-02-15 09:06发布

问题:

I'm a complete Rails n00b and i'm sure this is an easy thing to do but i'm having trouble. I would like to take the value of a key in my URL and set it to the :category_id of a record in my database as i import that record from csv.

i can get it to work by creating a category_id field in my csv file and using the following code to import the file

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

But that requires adding the category_id to the csv.. what I would like to do is something like

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

where @category is set in the URL. Something like: ...localhost:3000/manufacturers/import_manufacturer/2?category_id=2 this saves my record but sets the category id to "null" - this is the server output:

Started POST "/manufacturers/import?category_id=2" for 127.0.0.1 at 2013-07-18 11:19:55 +0200
Processing by ManufacturersController#import as 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`.* FROM `categories` WHERE `categories`.`id` = 2 LIMIT 1
Manufacturer Load (0.6ms)  SELECT `manufacturers`.* FROM `manufacturers` WHERE `manufacturers`.`category_id` IS NULL AND `manufacturers`.`name` = 'CITROEN' ORDER BY `manufacturers`.`id` ASC LIMIT 1
 (0.3ms)  BEGIN
SQL (0.5ms)  INSERT INTO `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`.* FROM `manufacturers` WHERE `manufacturers`.`category_id` IS NULL AND `manufacturers`.`name` = 'CITROEN' ORDER BY `manufacturers`.`id` ASC LIMIT 1
(0.2ms)  BEGIN
(0.1ms)  COMMIT

Is it possible to pass a variable into the csv.foreach loop like this?

Thanks in advance and sorry if I'm asking a stupid question.

回答1:

if the class method import is called in the import controller action, you can pass params[:category_id] as the 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) do |row|
      record = Manufacturer.where(
        :category_id => category_id,
        :name => row[0]
      ).first_or_create
    end
  end
end