【问题标题】:How do you render hashes as JSON in Rails 3如何在 Rails 3 中将哈希呈现为 JSON
【发布时间】:2011-03-29 13:02:13
【问题描述】:

我发现了如何在 Rails 3 中渲染 ActiveRecord 对象,但是我不知道如何渲染任何自定义对象。我正在编写一个没有 ActiveRecord 的应用程序。我试着做这样的事情:

class AppController < ApplicationController
  respond_to :json

  ...
  def start
    app.start
    format.json { render :json => {'ok'=>true} }
  end
end

【问题讨论】:

    标签: ruby-on-rails json api ruby-on-rails-3


    【解决方案1】:

    当您指定respond_to 时,您将在您的操作中进行匹配的respond_with

    class AppControlls < ApplicationController
      respond_to :json
    
      def index
        hash = { :ok => true }
        respond_with(hash)
      end
    end
    

    您似乎将旧的 respond_to do |format| 样式块与新的 respond_torespond_with 语法混为一谈。 This edgerails.info post 解释的很好。

    【讨论】:

      【解决方案2】:
      class AppController < ApplicationController
      
      respond_to :json
      
      def index
        hash = { :ok => true }
        respond_with(hash.as_json)
      end
      
      end
      

      您永远不应该使用 to_json 来创建表示,而只是使用该表示。

      【讨论】:

        【解决方案3】:

        format.json { render json: { ok: true } } 应该可以工作

        【讨论】:

          【解决方案4】:

          这非常接近。但是,它不会自动将散列转换为 json。这是最终结果:

          class AppControlls < ApplicationController
            respond_to :json
          
            def start
              app.start
              respond_with( { :ok => true }.to_json )
            end
          end
          

          感谢您的帮助。

          【讨论】:

          • { :ok => true }.json 给出 NoMethodError: undefined method `json' for {:ok=>true}:Hash
          • to_json 没有给出错误,但我相信它不是必需的。 (自动转换对我来说很好)。笔记。自动转换工作:格式必须是 json。
          【解决方案5】:

          对于那些得到 NoMethodError 的人,试试这个:

          class AppController < ApplicationController
            respond_to :json
          
            ...
            def start
              app.start
              render json: { :ok => true }
            end
          end
          

          【讨论】:

            猜你喜欢
            • 2011-06-16
            • 1970-01-01
            • 2011-01-28
            • 1970-01-01
            • 1970-01-01
            • 2011-05-08
            • 1970-01-01
            • 1970-01-01
            • 2021-12-03
            相关资源
            最近更新 更多