【发布时间】:2014-12-17 00:31:39
【问题描述】:
我对数据库关系的工作方式感到困惑。
假设我有一个过境点('crossing'),它有两个 Directions('north', 'south'),每个方向有2种车道('normal','fast'),每个车道有2个metrics(=data)('delay','queue_length') .
实际上有多个交叉口,具有更多车道类型和更多指标。
我应该如何将它存储在数据库中?我以前使用过数据库,但从未使用过表连接或一对多或类似的东西。
我遇到了 Datamapper,因为我正在学习如何使用 Sinatra,所以我想我会试一试。 在教程(http://datamapper.org/getting-started.html)中,“一对多”部分只是尖叫“这就是你需要的”,所以我开始摆弄。
require 'data_mapper'
DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/development.db")
class Crossing
include DataMapper::Resource
property :id, Serial
property :name, String,:unique=>true
has n, :directions
end
class Direction
include DataMapper::Resource
property :id, Serial
property :direction, String,:unique=>true
belongs_to :crossing
has n, :lanes
end
class Lane
include DataMapper::Resource
property :id, Serial
property :lane, String
belongs_to :direction
has n, :datas
end
class Data
include DataMapper::Resource
property :id, Serial
property :name, String,:unique=>true
property :value, String
belongs_to :lane
end
DataMapper.finalize.auto_migrate!
我只是觉得这看起来很优雅:“十字路口有 n 个方向,方向有 n 个车道,等等”
然后:
Crossing.create(:name => "crossing")
Direction.create(:direction => "north")
Direction.create(:direction => "south")
Lane.create(:lane => 'normal')
Lane.create(:lane => 'fast')
Data.create(:data => 'delay')
Data.create(:data => 'queue_length')
// now how do I retrieve find the data of a lane of a direction of a crossing?
现在,我将一直输入和检索的是数据部分。这整件事是否有意义,或者我只是不明白表关联的用途是什么?我知道我可以用一个巨大的物体代替这个,但我很确定这是一种奇怪的做事方式。
@crossing = {
'crossing name' => {
:directions => {
:north => {
:normal => {
:delay => '10 min',
:queue => '100 m'
},
:fast => {
:delay => '1 min',
:queue => '10 m'
}
},
etc etc etc
}
然后访问@crossing[:north][:normal][:delay] 之类的数据....但我觉得数据库会更好?
我有任何意义吗?有人指点一下年轻的蚂蚱吗?
【问题讨论】:
标签: ruby database ruby-datamapper