我试图从我的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
因此,它看起来像它在这里返回一个哈希,但我已经尝试了一堆东西,还没有想出我也应该跟我的末日协会合作。我怎样才能做到这一点?
谢谢!