[英]Ruby Sinatra Datamapper/database confusion
我對數據庫關系的工作方式感到困惑。
假設我有一個Border Crossing('crossing'),它有兩個Directions('north','south'),每個Directions有2種類型的車道('normal','fast'),每種車道都有2個指標(= data)(“延遲”,“隊列長度”)。
實際上,存在多個交叉路口,具有更多的車道類型和更多的指標。
我應該如何將其存儲在數據庫中? 我以前使用過數據庫,但從未使用過表聯接或一對多或類似的操作。
我遇到了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]之類的數據。...但是我有點想數據庫會更好?
我有任何意義嗎? 有人為年輕的草農找到了一些指示嗎?
我寧願使用這種結構:
Data
屬於Crossing
, Direction
和Lane
; 它具有delay
和queue
屬性 Direction
有許多Data
,並且正好有兩行 Lane
有很多Data
,並且正好有兩行 Crossing
有很多Data
,並且有很多行 原因是,您不想在數據庫中重復字符串"north"
, "south"
等。
然后,首先使用常量表為數據庫添加種子:
Direction.create(direction: 'north')
Direction.create(direction: 'south')
Lane.create(lane: 'normal')
Lane.create(lane: 'fast')
然后,您可以進行過境:
cool_crossing = Crossing.create(name: 'My Cool Crossing')
not_cool_crossing = Lane.create(name: 'My Not So Cool Crossing')
並添加數據點:
north = Direction.first(name: "north")
normal = Lane.first(name: "normal")
Data.create(
crossing: cool_crossing,
lane: normal,
direction: north,
delay: 10,
queue: 1
)
並通過以下方式檢索數據:
all_data_for_cool_crossing = Data.all(
crossing: cool_crossing
)
要么
data_for_cool_crossing_normal_north = Data.first(
crossing: cool_crossing,
lane: normal,
direction: north
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.