发送json_response时无法与ActiveRecord数据包含关系

问题描述 投票:0回答:1

我需要得到这样的答复:

{ 
  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_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']
}

render json: {
  unit_id: @unit.id,
  active_unit_plant: @unit.active_unit_plant,
  notifications: @notifications.includes(:grow_notification), include: ['grow_notification']
}

我没有在JSON中获得.grow_notification对象。

ruby-on-rails json activerecord
1个回答
0
投票

作为render here的参考用法:

render(options = nil, extra_options = {}, &block)

下面的代码不起作用,因为您将include: ['grow_notification']放在了第二个options的第一个参数extra_options中>

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']
© www.soinside.com 2019 - 2024. All rights reserved.