Rails API,如何设置/覆盖处理程序

时间:2016-04-10 20:48:31

标签: ruby-on-rails rest

我正在尝试将Rails MVC控制器扩展到不同的命名空间,并让子类充当REST api来接受并返回JSON而不是处理视图。

#include <iostream>

int main() {
  char inp[4] = {'O','I','L', '\0'};
  int lll = 4;
  // initialize elements of 'ARR' to 0 for safety
  char ARR[4] = {0};
  int subscount = 0;

  // dynamic allocation, DO NOT forget to de-allocate
  char* issub = new char[lll];
  // copy every element of 'inp' to 'issub'
  for(int i=0;i<lll;i++) {
    issub[i]=inp[i];
  }
  // this will copy where '*issub' points to,
  // that is the 'issub[0]', to 'ARR[subscount]'
  ARR[subscount] = *issub;
  std::cout << ARR << "\n"; // prints: O
  // you can use a for loop as before to copy the contents,
  // from 'inp', 'issub' to 'ARR'

  // However, we will do something different here,
  // so I am de-allocating 'issub'
  delete [] issub;

  // We will use an array of pointers, with size 2,
  // thus it will have two pointers in total.
  char* ptr_arr[2];

  // Assign the first pointer to 'inp'
  ptr_arr[0] = &(inp[0]);

  std::cout << ptr_arr[0] << "\n"; // prints OIL

  // we don't use the second pointer,
  // set it to NULL
  ptr_arr[1] = NULL;
  return 0;
}

但是,当我调用/ api / v1 / companies route时,我收到错误“Missing Template”,抱怨没有视图。在细节上,我看到一些处理程序让我觉得它正在尝试处理.erb文件。

Rails.application.routes.draw do

  resources :companies

  namespace :api do
    namespace :v1, defaults: { format: :json} do
      resources :companies
    end
  end

这是我的api / v1 / companies_controller

    Missing template api/v1/companies/show, companies/show, application/show with
 {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee]}.

有什么方法可以让rails不会试图找到一个视图模板而只返回json?

1 个答案:

答案 0 :(得分:1)

它应始终呈现为JSON

class Api::V1::CompaniesController < CompaniesController
  respond_to :json

  def show
    respond_with(@object) # pass your own object 
  end

end