【问题标题】:How to check existance and nil in single line for variable in ruby on rails如何在 ruby​​ on rails 中检查单行变量的存在和 nil
【发布时间】:2015-12-28 11:09:57
【问题描述】:
 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

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

【问题讨论】:

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


    【解决方案1】:

    试试这个:

    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
    

    【讨论】:

    • 得到错误“未定义的方法`update_all'”@Kkulikovskis
    • 但适用于 Spree::Product.find(row["id"]).update_attributes(hash)
    猜你喜欢
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 2012-12-28
    • 2011-03-29
    相关资源
    最近更新 更多