3

我是一个完整的 Rails n00b,我确信这很容易做到,但我遇到了麻烦。当我从 csv 导入该记录时,我想在我的 URL 中获取一个键的值并将其设置为数据库中记录的 :category_id 。

我可以通过在我的 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

但这需要将category_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

其中@category 在URL 中设置。类似于: ...localhost:3000/manufacturers/import_manufacturer/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 循环中?

如果我问的是一个愚蠢的问题,请提前致谢。

4

1 回答 1

4

如果在导入控制器操作中调用了类方法,则可以作为第二个参数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
于 2013-07-18T09:40:27.390 回答