Ruby on rails 无法。在发送json\u响应时包含与ActiveRecord数据的关系
我需要得到这样的答复:Ruby on rails 无法。在发送json\u响应时包含与ActiveRecord数据的关系,ruby-on-rails,json,activerecord,Ruby On Rails,Json,Activerecord,我需要得到这样的答复: { unit_id: 5, notifications: [ { id: 123, unit_id: 5, created_at: 2020-01-24T16:42:20.000Z, grow_notification_id: 59: grow_notification: { id: 59, title: "Update 6.0.0",
{
unit_id: 5,
notifications: [
{
id: 123,
unit_id: 5,
created_at: 2020-01-24T16:42:20.000Z,
grow_notification_id: 59:
grow_notification: {
id: 59,
title: "Update 6.0.0",
full_content: "Introducing fresh push notifications! We...",
...
},
...
]
}
}
我知道我可以在@unit.notifications.include:grow\u notifications做一些事情,但它没有给我想要的格式
唯一起作用的是当我这样做的时候:
@notifications = @unit.notifications
render json: @notifications.includes(:grow_notification), include: ['grow_notification']
但是,如果我尝试这样做:
render json: {
unit_id: @unit.id,
notifications: @notifications.includes(:grow_notification), include: ['grow_notification']
}
或
我没有在JSON中获得.grow_通知对象。作为render的参考用法:
下面的代码不起作用,因为您将include:['grow\u notification']放在了第一个参数选项中,而它应该是第二个额外的参数选项
正确用法:
render json: {
unit_id: @unit.id,
notifications: @notifications
}, include: ['grow_notification']
是的,我知道我的语法错了。实际上,我现在正在尝试使用json_响应,但我在网上唯一能找到的是scotch.io。你知道我该怎么做吗:json_响应{unit_id:@unit.id,通知:@notifications.include:grow_notification}带有grow_通知:{}blob?json_响应是一个单独的gem特性吗?
render(options = nil, extra_options = {}, &block)
render json: {
unit_id: @unit.id,
notifications: @notifications.includes(:grow_notification), include: ['grow_notification']
}
render json: {
unit_id: @unit.id,
notifications: @notifications
}, include: ['grow_notification']