Rails 4 CSV导入值并将值设置为键值

我是一个完整的Rails n00b,我确信这是一件容易的事,但我遇到了麻烦。 我想在我的URL中获取密钥的值,并将其设置为我的数据库中记录的:category_id,因为我从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 

但是这需要将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=#, @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