2017-09-17 107 views
1

我試圖從我的Sinatra REST API返回json格式的數據。我目前有一些關聯設置,但是我很難從我的API中獲得我想要的視圖,儘管它們很容易在Ruby中獲得。通過Sinatra獲得續集關聯

例如,從我的表:

DB.create_table?(:calendars) do 
    primary_key :id 

end 

DB.create_table?(:schedules) do 
    primary_key :id 

    foreign_key :resource_id, :resources 
    foreign_key :task_id, :tasks 
    foreign_key :calendar_id, :calendars 
end 

在Ruby中,我能夠運行一個塊這樣的,並顯示我通過協會需要的所有信息:

Calendar.each do |c| 
    c.schedules.each do |s| 
    puts "RESOURCE ##{s.resource_id}" 
    s.tasks.each do |t| 
     p t 
    end 
    puts 
    end 
end 

的由於我的calendar模型包含one_to_many :schedules關聯,所以請致電我的電話號碼爲c.schedules。現在

,我不知道如何轉換到我的西納特拉API。在我的簡單GET路線,我已經嘗試了許多變化試圖獲得與日曆有關的計劃,並將其轉換爲JSON:

get '/calendars' do 
    c = DB[:calendar].first 
    c.schedules.to_json 
    content_type :json 
end 

...但我會像undefined method 'schedules' for {:id=>1}:Hash

錯誤結束

因此,它看起來像它在這裏返回一個哈希,但我已經嘗試了一堆東西,還沒有想出我也應該跟我的末日協會合作。我怎樣才能做到這一點?

謝謝!

回答

0

的原因,你的第一個塊的作品,但第二次卻不會是因爲在第一種情況下,你使用Calendar類的續集模型實例,而在第二種情況下,您使用的是續集dataset

當您遍歷Calendar.each do |c|時,c變量將填充類Sequel模型對象的Calendar實例。此對象定義了關係方法(one_to_many),您可以查詢schedules並在其上運行其他模型方法。

然而,c = DB[:calendar].first讓你一個Sequel dataset。該對象與模型實例不同,它返回一個標準的Ruby散列(或散列數組)。

你可以改變你的第二塊使用模型來代替,它會得到你想要的結果:

get '/calendars' do 
    c = Calendar.first # <=== CHANGE FROM DATASET TO MODEL 
    c.schedules.to_json 
    content_type :json 
end