【问题标题】:Empty response from Rails JBuilderRails JBuilder 的空响应
【发布时间】:2015-01-16 07:44:06
【问题描述】:

有以下jbuilder模板:

json.extract! @order do |order|
    json.id                                         order.id
    json.room                                   order.room
    json.note                                   order.note
    json.order_status_id                order.order_status_id
    json.created_at                         order.created_at
    json.restaurant_order_items order.restaurant_order_items

    json.restaurant do
        json.id      order.restaurant.id
        json.email order.restaurant.email
        json.phone order.restaurant.phone

        json.place do
            json.title order.restaurant.place.title
        end
    end
end

我不明白为什么,但响应是“{}”。所以,我需要得到类似“{ id: 10, ... }”的响应。我该怎么做?谢谢!

【问题讨论】:

  • 这个答案对你有用吗?如果是,请接受,否则请更新问题并提供更多详细信息。谢谢!

标签: ruby-on-rails json jbuilder


【解决方案1】:

问题是extract! 只返回指定的属性,它不使用给定的块。

json.extract!(@order, :id, :note)
# => {"id":1,"note":"test"}

除了调用extract!方法,还可以使用调用语法:

json.(@order, :id, :note)
# => {"id":1,"note":"test"}

考虑到这一点,您可以像这样开始创建模板:

json.(@order, :id, :note)

json.restaurant do
  json.(@order.restaurant, :phone)
end

# => {"id":1,"note":"test","restaurant":{"phone":"123"}}

请注意,如果生成的 JSON 键的名称与对象上的属性相同,则无需提及两次。

json.(@order, :id)
# vs
json.id @order.id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2012-10-03
    • 2014-01-09
    • 2020-06-21
    • 2013-01-29
    • 2023-04-09
    相关资源
    最近更新 更多