【问题标题】:How to return non-entity json from a controller如何从控制器返回非实体 json
【发布时间】:2014-02-23 12:26:46
【问题描述】:

我正在制作一个 rest api,并有几个使用 respond_to 和 respond_with 的控制器,一切正常。

class ItemController < ApiController
    respond_to :json
    def index
       respond_with Item.all
    end
end

我希望控制器返回不基于实体的 JSON

class ReportController < ApiController

    def index
         @mylist << {
              :id => 1,
              :name => "test"
         }
         what goes here to return @mylist as json ?
    end
end

我尝试了几种不同的返回 @mylist 变体,这给了我类似的错误

nil:NilClass 的未定义方法 `

提前致谢!

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    要解决错误undefined method &lt;&lt; for nil:NilClass.,需要初始化变量。

    class ReportController < ApiController
    
        def index
             @mylist = []
             @mylist << {
                  :id => 1,
                  :name => "test"
             }
        end
    end
    

    【讨论】:

      【解决方案2】:

      这样做:

      render json: @mylist
      

      或:

      respond_with @mylist
      

      并以这种方式修复您的变量:

       @mylist = [ { id: 1, name: "test" } ]
      

      【讨论】:

        猜你喜欢
        • 2018-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多