2017-03-01 152 views
0

由于Datamapper,我试图访问我现有的数据。 但它不起作用。所有的方法,如.first,.all,...什么都不返回。 .update返回undefined method update for nil:NilClass (NoMethodError) ...为什么datamapper方法不起作用?

我敢肯定,该数据库是不是空的,因为这个代码回报很好的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 

回答

0

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

它看起来是因为您指定喜欢你的对象是无效的:

property :refund, Text, required: true 

如果要求退款,你需要指定它还是你的对象将不保存。

注意puts new_consultation.date作品,因为date仍保存在本地对象,即使save失败,并没有数据被保存到数据库中。

+0

谢谢@eiko的回答。其实我不想要退款。但我试图删除'required:true',我得到这个错误:“NOT NULL约束失败:consultation.refund(DataObjects :: IntegrityError)”。为了测试,我尝试让'refund'属性设置为'require:true'并设置它('new_consultation.refund =“no”'),然后你就写了,因为它工作正常!但是我可以在不出现这个错误的情况下删除'require:true',你知道我该如何解决这个问题吗? – Orsay

+0

@Orsay你可以尝试专门把'require:false'看看是否有用吗? – eiko

+0

如果我把'require:false'并仍然设置它('consultation.refund ='不退款')'它的工作原理。但是,如果我不设置它,我会得到'NOT NULL约束失败:consultation.refund(DataObjects :: IntegrityError)' – Orsay

相关问题