Rails 4 CSV导入和将一个值设置为一个关键值[英] Rails 4 CSV Import and setting a value to a key value

问题描述

我是一个完整的Rails N00B,我敢肯定这是一件容易的事,但是我遇到了麻烦.我想将URL中的密钥值拿到:从CSV导入该记录.

我可以通过在我的CSV文件中创建一个category_id字段并使用以下代码导入文件

来使它起作用.
  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

,但这需要将类别_id添加到CSV中.我想做的是

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

在URL中设置@Category的其中.就像是: ... localhost:3000/制造商/import_manfucturer/2?category_id = 2 这保存了我的记录,但将类别ID设置为" null" - 这是服务器输出:

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

是否可以将变量传递到csv.foreach循环中?

提前感谢,对不起,如果我问一个愚蠢的问题.

推荐答案

如果类方法import在导入控制器操作中调用,则可以将params[:category_id]传递为第二个参数.

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

本文地址:https://www.itbaoku.cn/post/584858.html