【发布时间】:2011-11-23 05:33:14
【问题描述】:
好的,这让我发疯了。我已经阅读了协会的文章和示例,并且在过去的三天里一直在努力解决这个问题,我厌倦了这让我感到愚蠢,所以......
如何与 DataMapper 建立关联?
(我正在使用带有 SQLite3 的 Sinatra 的 DM。对于具有多个值等的单个表来说,一切都很好。当我开始尝试将它们关联起来时,我开始遇到错误。)
假设我有一个种满苹果树的果园。每棵树都有很多苹果。每个苹果都有许多种子。因此,每棵树的苹果都有很多种子
require 'sinatra'
require 'datamapper'
DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/orchard.db")
# Trees in the orchard.
class Tree
include DataMapper::Resource
property :id, Serial
has n, :apples
has n, :seeds, :through => :apples
end
# Apples on a Tree.
class Apple
include DataMapper::Resource
property :id, Serial
belongs_to :tree
belongs_to :seed
end
# Seeds in an Apple
class Seed
include DataMapper::Resource
property :id, Serial
has n, :apple
has n, :tree, :through => apple
end
DataMapper.finalize.auto_upgrade!
正确吗?当我尝试运行它时,我不断收到各种错误。主要是无效关联或无法创建值为 NULL 的列 NULL 等。我对这种关系有什么不了解?
此外,一旦我有了一个工作模型,我该如何从中获取信息?
如果有 3 棵树:
Tree.all.count
=> 3
如果有 2 个苹果:
Apple.all
=>[#<Apple @id=1>, #<Apple @id=2>]
好的,酷。 但是树#2 有多少个苹果呢? 树#4有多少种子? 一共有多少个苹果? 一共有多少颗种子?
任何帮助将不胜感激。
【问题讨论】:
标签: ruby sinatra datamapper