2013-07-18 23 views
3

我是一个完整的Rails n00b,我确信这是一件容易的事情,但我遇到了麻烦。我想在我的URL中获取一个键的值,并将其设置为我的数据库中记录的category_id,因为我从csv导入该记录。Rails 4 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中。喜欢的东西: ...本地主机:3000 /厂商/ import_manufacturer/2 CATEGORY_ID = 2 这节省了我的纪录,但设置类别ID为 “空” - 这是服务器输出:

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

如果在导入控制器操作中调用类方法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 
+0

辉煌 - 这工作的一种享受。我相信我可能应该知道,但..需要更多的学习:) - 谢谢 –