通过 Sinatra 获得 Sequel 个关联

Getting Sequel associations through Sinatra

我正在尝试从我的 Sinatra REST API return json 格式化数据。我目前建立了一堆协会,但我无法从我的 API 获得我想要的观点,尽管在 Ruby.

中很容易获得它们

例如,从我的表中:

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

c.schedules 调用有效,因为我的 calendar 模型包含一个 one_to_many :schedules 关联。

现在,我想知道这如何转化为我的 Sinatra 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

这样的错误

所以它看起来像是 return 在这里散列,但我已经尝试了很多东西但还没有弄清楚我应该如何在 Sinatra 中使用我的关联。我该怎么做?

谢谢!

你的第一个块工作但第二个不工作的原因是因为在第一种情况下,你使用的是 Sequel 模型实例 of class Calendar,而在第二种情况下,您使用的是 Sequel dataset.

当您迭代 Calendar.each do |c| 时,c 变量会填充 Calendar class Sequel 模型对象的实例。此对象定义了关系方法 (one_to_many),您可以在其上查询 schedules 和 运行 其他模型方法。

但是,c = DB[:calendar].first 会给你一个 Sequel dataset。此对象不同于模型实例,它 returns 标准 Ruby 散列(或散列数组)。

您可以更改您的第二个块以改用模型,它将获得您想要的结果:

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