【问题标题】:Rabl showing an empty json blockRabl 显​​示一个空的 json 块
【发布时间】:2013-08-22 19:37:40
【问题描述】:

我正在尝试 Rabl,但是,我似乎收到了一个几乎空的 json 块。

require_dependency "api/application_controller"

module Api
  class RentablePropertiesController < ApplicationController
    respond_to :json
    def index
      @r = Core::RentableProperty.all
      # render :text => @r.to_json  --> note: this renders the json correctly
      render "api/rentable_properties/index"  #note: rabl here does not
    end
  end
end

index.json.rabl collection @r

输出

[{"rentable_property":{}}]

注意:使用简单的@r.to_json,它可以正确呈现:

[{"id":1,"description":"description","property_type_id":1,"created_at":"2013-08-22T19:04:35.000Z","updated_at":"2013-08-22T19:04:35.000Z","title":"Some Title","rooms":null,"amount":2000.0,"tenure":null}]

知道为什么 rabl 不起作用吗?

【问题讨论】:

  • github.com/nesquena/rabl#overview 查看概述部分,它说您需要在 index.json.rabl 中精确显示要显示的属性
  • 哈哈太棒了!如果您将其添加为答案,我会将其标记为已接受;)
  • 顺便说一句,为什么每个实例都有键“rentable_property”?
  • 我根本不知道RABL,最后一个问题我帮不上忙,对不起

标签: ruby-on-rails ruby json rabl


【解决方案1】:

RABL (https://github.com/nesquena/rabl#overview) 的文档说,您需要明确要在 JSON 中显示的属性。

他们的例子:

# app/views/posts/index.rabl
collection @posts
attributes :id, :title, :subject
child(:user) { attributes :full_name }
node(:read) { |post| post.read_by?(@user) }

访问/posts.json时会输出以下JSON或XML:

[{  "post" :
  {
    "id" : 5, title: "...", subject: "...",
    "user" : { full_name : "..." },
    "read" : true
  }
}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    相关资源
    最近更新 更多