【问题标题】:Rails - blank json file when using jbuilderRails - 使用jbuilder时的空白json文件
【发布时间】:2012-10-03 05:31:08
【问题描述】:

我正在尝试使用 jbuilder 从事件列表中创建一个 json 文件。它必须采用特定格式。目前,无论我在 jbuilder 文件中放入什么,当您转到 users/1/events.json 时,该文件都是空白的(只是 {})。

我已经尝试在控制器中放置一个响应块,但是这只是以错误的格式返回事件列表。

我认为路由已正确完成,因为日志文件显示文件 myevents.json.jbuilder 在请求 url /users/1/myevents.json 时成功呈现。另外,当请求 .html 时,myevents.html 文件显示正常,其中包含所有正确信息。

我真的很难过这个,任何帮助将不胜感激!

我会列出所有相关的代码,以防任何人都可以拿起一些东西:

事件控制器:

def myevents
    @events = current_user.events
end

myevents.json.jbuilder:

Jbuilder.encode do |json|
    json.timeline do
        json.headline current_user.first_name
        json.type "default"
        json.text "A Timeline"
        json.start_date
        json.array!(@events) do |event|
            json.start_date event.start_date
            json.end_date event.end_date
            json.headline event.headline
            json.text event.text
            json.asset do
                json.media event.media
                json.credit event.credit
                json.caption event.caption
            end
        end
    end
end

环境.rb:

Jbuilder.key_format :camelize => :lower

routes.rb:

match 'users/:id/events' => 'events#myevents'

【问题讨论】:

  • 你使用的是什么版本的 Rails?

标签: ruby-on-rails json routes jbuilder


【解决方案1】:

想通了。出于某种原因,它不喜欢 Jbuilder.encode do |json| 这一行,尽管这是要使用的文档中列出的内容。响应的语法仍然不太正确。

【讨论】:

    【解决方案2】:

    据我所知你可以跳过

    Jbuilder.encode

    尝试不使用此块,也许一切都会好起来的。

    【讨论】:

    • 我得到“未定义的局部变量或方法'json'”
    【解决方案3】:

    原因是你需要在你的 RSPEC 控制器帮助文件中加入下面一行:

    config.render_views = true
    

    我遇到了同样的问题:https://github.com/rails/jbuilder/issues/32

    【讨论】:

      猜你喜欢
      • 2012-10-03
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 2017-12-24
      • 2014-02-18
      • 1970-01-01
      相关资源
      最近更新 更多