2017-03-01 16 views
0

私はDatamapperのおかげで私の既存のデータにアクセスしようとしました。 しかし、それは動作しません。 .first,.allのようなすべてのメソッドは何も返しません。なぜdatamapperメソッドが機能しないのですか?

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チェックに:undefined method update for nil:NilClass (NoMethodError) ...

を返す.update私は、これは全体のコードであるだけでなく、このコードリターンので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 

データベースが空ではないと確信しています保存する前にオブジェクトが有効かどうかを確認してください。オブジェクトが有効な場合は、保存してtrueを返します。それ以外の場合は、保存せずに `falseを返します。

、指定したので、あなたのオブジェクトが無効であるように見えます:

property :refund, Text, required: true 

払い戻しが必要な場合は、あなたがそれを指定するか、あなたのオブジェクトは保存されません必要があります。

saveが失敗し、データがデータベースに保存されていない場合でも、dateがローカルオブジェクトに保存されているため、puts new_consultation.dateが機能することに注意してください。

+0

お返事ありがとう@eiko実際、私は「払い戻し」が必要であるとは思わない。しかし、私は 'required:true'を削除しようとしました。このエラーが発生しました:" NOT NULL制約が失敗しました:consultations.refund(DataObjects :: IntegrityError) "。テストするために、 'refund'属性を' require:true'に設定してそれを設定してみましょう( 'new_consultation.refund =" no "')。しかし、私は 'require:true'をこのエラーを出すことなく削除することができます。どうすればそれを修正できますか? – Orsay

+0

@Orsay特に動作するかどうかを確認するために 'require:false'を置くことができますか? – eiko

+0

'require:false'を入れてそれを設定していれば( 'consultation.refund = 'no refund')'それが動作します。しかし、私がそれを設定しなければ、NOT NULL制約が失敗します:consultations.refund(DataObjects :: IntegrityError) ' – Orsay

関連する問題