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

发布于 2024-12-04 05:11:12 字数 794 浏览 3 评论 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 是哈希(键:测试,值:字符串)

My models:

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

Why this code raises an SaveFailureError?:

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

where variable @results is Hash (keys: Test, values: String)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若有似无的小暗淡 2024-12-11 05:11:12

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

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

It raises error because child objects are not saved. Try this:

@results.each do |test, result|
  TestVisit.create(:visit => @visit, :test => test, :result => result)
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文