2015-12-28 19 views
0
def import_update 
    require 'csv' 
    file = params[:file] 
    CSV.foreach(file.path, headers: true) do |row| 

@prod = Spree::Product.find(row["id"]) 
@var = Spree::Variant.find_by(product_id: @prod.id) 
Spree::Product.where(:id => row["id"]).update_all(:name => row["name"] if !row[name].nil?.present?, :meta_description => row["meta_description"], :shipping_category_id => row["shipping_category_id"], :description => row["description"], :meta_keywords => row["meta_keywords"], :tax_category_id => row["tax_category_id"], :available_on => row["available_on"], :deleted_at => row["deleted_at"], :promotionable => row["promotionable"], :meta_title => row["meta_title"], :featured => row["featured"], :supplier_id => row["supplier_id"]) 
      end 
end 

我想檢查該行是否存在或不存在。如果它存在,那麼它在非空時更新,條件在單行中,因爲我想將這個應用於更新語句中的所有變量。我在上面編寫代碼,但是顯示錯誤。如何檢查存在和無在單線紅寶石軌道上的變量

回答

0

試試這個:

params = ["name","meta_description","shipping_category_id","description","meta_keywords","tax_category_id","available_on","deleted_at","promotionable","meta_title","featured","supplier_id" 
hash = {} 

params.each do |param| 
    if row[param] 
    hash[param] = row[param] 
    end 
end 
Spree::Product.where(:id => row["id"]).update_attributes(hash) 

這將讓你保持你的代碼幹。

編輯:

這些是什麼人行應該做的?:

@prod = Spree::Product.find(row["id"]) 
@var = Spree::Variant.find_by(product_id: @prod.id) 

我想你不會有一個ID多個條目。而你不使用你的這兩行檢索的對象,所以乾脆寫這樣的方法:

def import_update 
    require 'csv' 
    file = params[:file] 
    params = ["name","meta_description","shipping_category_id","description","meta_keywords","tax_category_id","available_on","deleted_at","promotionable","meta_title","featured","supplier_id"] 
    CSV.foreach(file.path, headers: true) do |row| 
     hash = {} 
     params.each do |param| 
     if row[param] 
      hash[param] = row[param] 
     end 
     end 
     Spree::Product.find(row["id"]).update_all(hash) 
    end 
end 
+0

得到錯誤「未定義的方法'update_all」」 @Kkulikovskis –

+0

但施普雷作品:: Product.find(行[ 「ID」])。update_attributes方法(散列) –