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