为什么数据映射器方法不起作用?

Why datamapper methods doesn't work?

感谢 Datamapper,我尝试访问我现有的数据。 但它不起作用。 .first.all、... return 等所有方法都没有。 .update return 一个 undefined method update for nil:NilClass (NoMethodError)...

我确定数据库不为空,因为这段代码 return new_consultation.date

new_consultation = Consultation.new
new_consultation.name = name_prestation
new_consultation.expense = expense_prestation
new_consultation.date = date_prestation.empty? ? Time.now.strftime("%d/%m/%Y") : date_prestation 
new_consultation.save
puts new_consultation
puts new_consultation.date

这是完整的代码:

DataMapper.setup(:default, 'sqlite:medical_expenses.db')
class Consultation
  include DataMapper::Resource

  property :id, Serial
  property :name, Text, required: true
  property :expense, Text, required: true
  property :date, Text, required: true
  property :refund, Text, required: true 
end
DataMapper.finalize()
DataMapper.auto_upgrade!()

# Enter and save new consultation
puts 'Prestations ?'
name_prestation = gets.chomp
puts 'Montant ?' 
expense_prestation = gets.chomp
puts 'Date ? (par défaut date du jour)'
date_prestation = gets.chomp
print "Dépense enregistrée"

new_consultation = Consultation.new
new_consultation.name = name_prestation
new_consultation.expense = expense_prestation
new_consultation.date = date_prestation.empty? ? Time.now.strftime("%d/%m/%Y") : date_prestation 
new_consultation.save
puts new_consultation
puts new_consultation.date

Consultation.first.update(refund: 'none')
puts Consultation.first

new_consultation.save 在保存之前检查您的对象是否有效。如果对象有效,它会保存并且return true;否则,它不会保存并且 return `false.

您的对象似乎无效,因为您指定了:

property :refund, Text, required: true 

如果需要退款,您需要指定它,否则您的对象将不会保存。

请注意,puts new_consultation.date 有效,因为 date 仍存储在本地对象中,即使 save 失败并且 none 的数据已保存到数据库中。