在Rails中开发API的错误

时间:2015-05-22 12:05:27

标签: ruby-on-rails ruby ruby-on-rails-4

我开始使用RAILS开发API。我正在做一个我自己的简单例子,但是当我想在我的API中看到结果时,我有一个错误。

控制器:

class EnergyCalcController < ApplicationController
  def index
    file_path = Rails.root.join('db','test_file.js')  
     file_gen = File.read(file_path) 
     @data_hash_gen = JSON.parse(file_gen)  


  end
end

在controllers / api / energy_calc_controller.rb

class Api::EnergyCalcController < ApplicationController
    def index
        render json: @data_hash_gen 
    end

end

路线

Rails.application.routes.draw do
  namespace :api do
    resources :energy_calc
  end
  get 'energy_calc/index'

查看/ energy_calc / index.html.erb

<h1>EnergyCalc#index</h1>
<p>Find me in app/views/energy_calc/index.html.erb</p>
<%= @data_hash_gen %>

在视图中正常打印数据。但是当我尝试访问:http://localhost:3000/api/energy_calc.json时,我得到了null

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

EnergyCalcController索引方法代码放入Api::EnergyCalcController's索引方法中。像这样,

class Api::EnergyCalcController < ApplicationController
  def index
    file_path = Rails.root.join('db','test_file.js')  
    file_gen = File.read(file_path) 
    @data_hash_gen = JSON.parse(file_gen)  
    render json: @data_hash_gen 
  end

end

答案 1 :(得分:0)

你不需要有两个不同的控制器来渲染不同的格式。它是多余的。你可以在一个动作中渲染HTML和JSON。

class EnergyCalcController < ApplicationController

    def index
      file_path = Rails.root.join('db','test_file.js')  
      file_gen = File.read(file_path) 
      @data_hash_gen = JSON.parse(file_gen)  
      respond_to do |format|
        format.json {
          render :json => @data_hash_gen
        }
        format.html {
          #Objects exclusively needed to render html
        }
      end
    end

end