如何在 rails 上的 ruby 中单行检查变量是否存在和 nil

How to check existance and nil in single line for variable in ruby on rails

 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 并且条件在单行中时它会更新,因为我想将它应用于更新中的所有变量 statement.I 在上面写了代码但显示错误。

试试这个:

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