一对多 - 通过添加连接模型实例

时间:2011-09-10 16:19:59

标签: one-to-many datamapper has-many-through

我的模特:

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

为什么此代码会引发保存失败错误?:

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

其中变量@results是Hash(keys:Test,values:String)

1 个答案:

答案 0 :(得分:1)

它会引发错误,因为未保存子对象。试试这个:

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