2017-01-23 1 views
0

gem rooを使用してExcelファイルを使用してデータをインポートする際に、レールキャストチュートリアル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は=のために正しい形式でそのおそらくないものプリントアウトしてください:この方法@HoMan {キー値}' –

+0

は私が団体でレコードを作成することができますか? – LuisC

+0

@HoMan私がこれを行うとき:producto.attributes = {Clave:Clave} 私は次のエラーが発生します:未初期化定数Producto :: Clave – LuisC

答えて

1

は、正確には、productosxpzaに属性を設定したいのですが、プロダクトでは正しく機能しますか?これはうまくいくはずです。

producto.productosxpza_attributes = { ... } 
+0

それを修正し、関連するテーブルのデータをインポートしますが、私は小さなエラーが発生しましたが、既存のレコードをアップロードすると以前のように更新されませんでしたが、私にこのエラーが送信されます。テーブル 'AdvanceControl_Copy.dbo.ProductosXPzas';列はNULLを許可しません。 UPDATEが失敗します。EXEC sp_executesql N'UPDATE [productosxpzas] SET [Producto] = @ 0 WHERE [productosxpzas]。[IDP] = @ 1; @ 0、NULL = 0、@ 1 = 165 – LuisC

+0

productosxpzaも更新しようとしています:productosxpza = find_by_Producto(row ["Clave" ])||新しい producto.productosxpza_attributes = {PzaXCja:行["PzaXCja"]、Producto:行["Clave"]} producto.save! #(productosxpzaのproductoは外部キーです)が、同じエラーが発生します – LuisC

関連する問題