在它的模型上调用模型名称

时间:2013-03-04 11:49:43

标签: ruby-on-rails model

我有excel的导入功能。我把它放在我的模型上:

def self.import(file, employee_name)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    category = Category.where(:name => row["Category"]).last
    if category.blank?
      category = Category.create(:name => row["Category"], :is_active => 1)
    end
    unit = UnitOfMeasure.where(:name => row["Unit"]).last
    if unit.blank?
      unit = UnitOfMeasure.create(:name => row["Unit"], :is_active => 1)
    end

    chart_of_account_id=0
    stock_output_account=0

    if row["Can Sold"]==1
      income_account=1
    else
      income_account=0
    end

    if row["Can Purchased"]==1
      expense_account=1
    else
      expense_account=0
    end

    product = Product.create(:plu => row["PLU"], :plu_night_disc => row["PLU Night Disc."], :name => row["Item Desc."], :min_stock => ["Min. Stock"], :product_type => row["Product Type"], :notes => ["Notes"], :sales_price => ["Sales Price"], :night_disc_price => ["Night Disc. Price"], :bottom_price => ["Bottom Price"], :category_id => category.id, :unit_of_measure_id => unit.id, :chart_of_account_id => chart_of_account_id, :stock_output_account => stock_output_account, :income_account => income_account, :expense_account => expense_account, :can_be_sold => row["Can Sold"], :can_be_purchased => row["Can Purchased"], :employee_name => employee_name, :is_active => 1)

  end
end

但是当我执行导入时,它不会返回任何错误,但是我创建的Product只是跳过了(查找长代码),当我尝试更改Product时模拟Country它精确地插入数据库。我确实混淆了这种行为。请帮忙。感谢

1 个答案:

答案 0 :(得分:0)

您获得的这种行为可能意味着您有一个无效的Product记录,并且插入无声地失败。请尝试使用create!方法:

product = Product.create!(...)

如果您的模型无效,此方法将引发错误,并解释原因。您可以使用该信息来调试代码。

希望有所帮助。

相关问题