如何查找现有客户并将其分配给发票

How to find and assign an existing customer to invoice

您好,我有 2 个模型 CustomerInvoiceCustomer 有 2 个字段 nameemail,发票也有 2 个字段 nameamount.

Customer has_many invoices

Invoice belongs_to customer

我创建了一个导入方法:

  def self.import(file)
    CSV.foreach(file.path, headers:true, skip_lines: /^(?:,\s*)+$|\b(\w*Total\w*)\b/) do |row|      
      Invoice.create! row.to_hash
    end
  end

是否可以检查是否存在 customer.name == invoice.name 以及是否为真以获取 customer_id 并保存它。 谢谢

假设name字段在customerinvoicetable中都是唯一的,可以进行如下操作-

在您的 invoice 模型中使 belongs_to 可选 - belongs_to :customer, optional: true

def self.import(file)
  CSV.foreach(file.path, headers:true, skip_lines: /^(?:,\s*)+$|\b(\w*Total\w*)\b/) do |row|
    row = row.to_hash      
    invoice = Invoice.new(row)
    customer = Customer.find_by(name: row['name'])
    invoice.customer = customer if customer.present?
    invoice.save!
  end
end