我正在制作一个Ruby on Rails应用程序:
routes.rb
:
Test::Application.routes.draw do
get "api_error/404"
get "sss/home"
root :to => "home#index"
match "/zad0xsis" => "home#pablo"
match "/sss" => "sss#home"
match "/api/1/:api_action" => "api_v1#runner"
match "/api/" => "api_error#api_not_found"
match "/api/:api_version/:api_action" => "api_error#api_not_found"
match "/api/:api_version" => "api_error#api_not_found"
match "/api/1/:api_action/:whoiscool" => "api_v1#runner"
match "/whoscool/:whoiscool" => "api_v1#whoscool"
end
api_v1_controller.rb
:
class ApiV1Controller < ApplicationController
def runner
response.headers["Content-Type"] = 'application/json'
response.headers["Access-Control-Allow-Origin"] = '*'
response.headers["server"] = `hostname`
@output = {'api_version' => "1", "error"=>false}
case params[:api_action]
when "register"
register
when "whoscool"
whoscool
else
@output['error'] = true
@output['error_code'] = 106
@output['human_error'] = "API Function not found (or not authorized)"
end
# Set Output
@output = JSON.generate(@output)
# Turn Off Layout
render :layout => false
end
#--------------------------
# Register Action
#--------------------------
def register
@output['hello'] = "true"
end
def whoscool
@output['cool is'] = params[:whoiscool]
end
#----- ADD NEW FUNCTIONS ABOVE THIS LINE -------#
end
whoscool_controller.rb
:
class WhoscoolController < ApplicationController
def index
end
end
我需要知道如何whoscool_controller.rb
调用api_v1_controller.rb
runner
来调用行动whoscool
。如果我访问api/1/whoscool/zad0xsis
,我会得到正确的JSON输出,但是在访问whoscool/zad0xsis
时我需要获得该输出。谢谢!
答案 0 :(得分:0)
如果我没有正确地听到你的话,你想要做的是有两个不同的路径调用相同的功能,但使用不同的格式,只需添加几个路由,如下所示:
match 'whoscool/:id' => 'whoscool#show'
scope 'api/v1' do
match 'whoscool/:id' => 'whoscool#show', :format => 'json'
end
然后让WhoscoolController
处理不同的格式:
class WhoscoolController < ApplicationController
def show
respond_to do |format|
format.html { ... }
format.json { ... }
end
end
end