在没有Seri​​alizer的情况下自定义ActiveRecord JSON响应

时间:2015-04-20 00:20:28

标签: json api sinatra sinatra-activerecord

我使用sinatra / contrib渲染一些JSON。我想自定义我的JSON响应,不包括" teacher_id"在相关记录中。我该怎么做?

get '/teachers' do
  json Teacher.includes(:courses).all.as_json(include: :courses)
end

将呈现:

{
  "id": 1,
  "name": "Dave",
  "age": 27,
  "specialism": "Ruby",
  "courses": [
    {
      "id": 1,
      "title": "WDI",
      "teacher_id": 1
    }
  ]
}

我想删除,teacher_id:

{
  "id": 1,
  "name": "Dave",
  "age": 27,
  "specialism": "Ruby",
  "courses": [
    {
      "id": 1,
      "title": "WDI"
    }
  ]
}

我可以使用except:语法删除id,name,age和specialism。如何删除相关属性?

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以将:except选项用于以下关联:

Teacher.includes(:courses).all
  .as_json(include: { courses: { except: :teacher_id } })