【问题标题】:Rails 6 jbuilder not rendering array properlyRails 6 jbuilder没有正确渲染数组
【发布时间】:2019-10-04 08:43:47
【问题描述】:

我在使用 JBuilder on Rails 6(仅 API 模式)正确渲染数组时遇到问题。

我基本上有一个车牌列表,我想通过 API 请求获取它

我的索引视图如下所示:

# frozen_string_literal: true

json.array! @registration_plates,
            partial: 'registration_plates/registration_plate',
            as: :registration_plate


我的显示视图如下:

# frozen_string_literal: true

json.partial! 'registration_plates/registration_plate',
              registration_plate: @registration_plate


最后部分_registration_plate.json.jbuilder很简单:

# frozen_string_literal: true

json.id registration_plate.id
json.plate registration_plate.plate.to_s

我确实收到了来自服务器的正常响应:

但我得到的不是数组,而是一系列 JSON 对象

有没有人有类似的问题,或者你知道如何解决它?

比你提前。

编辑

我的控制器也被配置为渲染 jbuilder 而不是 json


  # GET /registration_plates
  def index
    @registration_plates = RegistrationPlate.all

    render @registration_plates
  end

  # GET /registration_plates/1
  def show
    render @registration_plate
  end

如果我将索引操作更改为看起来像

  def index
    @registration_plates = RegistrationPlate.all

    render json: @registration_plates.to_json(only: %i[id plate])
  end

我确实得到了正确的输出,但是我违背了 jbuilder 的唯一目的

【问题讨论】:

  • 你能尝试一件事吗...从你的 index 操作中删除 render @registration_plates

标签: ruby-on-rails json ruby-on-rails-6


【解决方案1】:

更新您的索引以删除 render @registration_plates

  # GET /registration_plates
  def index
    @registration_plates = RegistrationPlate.all
  end

render @registration_plates 直接渲染_registration_plate.json.jbuilder 而无需进入index.json.jbuilder

【讨论】:

  • 是的,就是这样。非常感谢朋友。
  • 乐于助人!!
猜你喜欢
  • 2014-06-01
  • 2016-04-29
  • 1970-01-01
  • 2018-05-04
  • 1970-01-01
  • 2018-12-17
  • 2020-05-12
  • 1970-01-01
  • 2021-07-22
相关资源
最近更新 更多