2017-01-23 35 views
0

我正在關注使用excel文件將數據導入到使用gem roo的數據庫的railcast教程https://www.youtube.com/watch?v=_NSBm_Q431Y&t=487s。導入和導出數據做工精細,但在導入關係型數據的時候它讓我看到以下錯誤:如何從excel文件導入關係數據

unknown attribute 'PzaXCja' for Producto. 
Extracted source (around line #73): 

     row = Hash[[header, spreadsheet.row(i)].transpose] 
     producto = find_by_Clave(row["Clave"]) || new 
     producto.attributes = row.to_hash.slice(*row.to_hash.keys) 
     producto.save! 
    end 
    end 

這是我的方法模型「PRODUCTO」:

has_one :productosxpza, class_name: "Productosxpza", foreign_key: "Producto" 
    accepts_nested_attributes_for :productosxpza 

    def self.to_csv(options = {})#exportar 
    CSV.generate(options) do |csv| 
     csv << column_names 
     all.each do |producto| 
     csv << producto.attributes.values_at(*column_names) 
     end 
    end 
    end 

    def self.import(file)#importar 
    spreadsheet = open_spreadsheet(file) 
    header = spreadsheet.row(1) 
    (2..spreadsheet.last_row).each do |i| 
     row = Hash[[header, spreadsheet.row(i)].transpose] 
     producto = find_by_Clave(row["Clave"]) || new 
     producto.attributes = row.to_hash.slice(*row.to_hash.keys) #*row.to_hash.keys para rails 4 que sustituye el attr_accesible de rails 3 
     producto.save! 
    end 
    end 

    def self.open_spreadsheet(file)#importar 
    case File.extname(file.original_filename) 
    when '.csv' then Roo::Csv.new(file.path, packed: false, file_warning: :ignore) 
    #when '.xls' then Roo::Excel.new(file.path, packed: false, file_warning: :ignore) 
    when '.xlsx' then Roo::Excelx.new(file.path, packed: false, file_warning: :ignore) 
    #else raise "Unknown file type: #{file.original_filename}" 
    else raise "El formato debe ser .xlsx ó .csv" 


    end 
    end 
+0

不要打印出來的變量行就是它可能不是在'producto.attributes =正確的格式{鍵:值}' –

+0

@HoMan這種方法可以讓我創建關聯的記錄? – LuisC

+0

@HoMan當我這樣做:producto.attributes = {Clave:Clave} 我得到以下錯誤:未初始化的常量Producto :: Clave – LuisC

回答

1

如果我有你是否正確,你想要在productosxpza上設置屬性,但通過產品權?這應該工作。

producto.productosxpza_attributes = { ... } 
+0

糾正它的工作,導入相關表中的數據,但現在我有一個小錯誤,當我上傳一個現有的記錄不像以前那樣更新它,但它給我發出這樣的錯誤:無法將值NULL插入'Producto'列,表'AdvanceControl_Copy.dbo.ProductosXPzas';列不允許有空值。 UPDATE失敗:EXEC sp_executesql N'UPDATE [productosxpzas] SET [Producto] = @ 0 WHERE [productosxpzas]。[IDP] = @ 1; SELECT @@ ROWCOUNT AS AffectedRows',N'@ 0 varchar(50),@ 1 int',@ 0 = NULL,@ 1 = 165 – LuisC

+0

我試試這個來更新productosxpza:productosxpza = find_by_Producto(row [「Clave」 ])||新 producto.productosxpza_attributes = {PzaXCja:row [「PzaXCja」],Producto:row [「Clave」]} producto.save! #(productosxpza中的producto是外鍵)但我得到相同的錯誤 – LuisC