2011-09-10 39 views
0

我的模型:一到多,通過將加入模型實例

class Test 
    include DataMapper::Resource 

    property :id, Serial 
    property :name, String, :default => '' 

    has n, :test_visits 
    has n, :visits, :through => :test_visits 
    # ... 
end 

class Visit 
    include DataMapper::Resource 
    property :id, Serial 
    property :name, String 

    has n, :test_visits 
    has n, :tests, :through => :test_visits 
    # ... 
end 

class TestVisit 
    include DataMapper::Resource 

    property :result, String 

    belongs_to :test, :key => true 
    belongs_to :visit, :key => true 
end 

爲什麼這個代碼引發SaveFailureError ?:

@visit.test_visits.clear 
@results.each do |test, result| 
    @visit.test_visits.new(:test => test, :result => result) 
end 
@visit.save 

其中變量@Results是哈希(鍵:測試,值:字符串)

回答

1

由於未保存子對象,所以會引發錯誤。試試這個:

@results.each do |test, result| 
    TestVisit.create(:visit => @visit, :test => test, :result => result) 
end 
相關問題