如何检查轨道上红宝石中变量的单线存在和零

时间:2015-12-28 11:09:58

标签: ruby-on-rails-4 rubygems spree

 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

我想检查行是否存在。如果它存在,那么当它不为null并且条件是单行时它会更新,因为我想在updation语句中将它应用于所有变量。我在上面写了代码但显示错误。

1 个答案:

答案 0 :(得分: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