【问题标题】:One-To-Many-Through adding join model instances一对多添加连接模型实例
【发布时间】:2011-09-10 16:19:59
【问题描述】:

我的模型:

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 是哈希(键:测试,值:字符串)

【问题讨论】:

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


    【解决方案1】:

    由于未保存子对象而引发错误。试试这个:

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

    【讨论】:

      猜你喜欢
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多