[英]Ruby on Rails: Reference to a singleton class action in routes
我正在尝试在 Rails 上使用 Ruby 在 class 上工作,以创建一个简单的 controller。 从这个意义上说,我有一个 singleton,我需要参考它的路线。 这怎么可能?
我得到的信息:
找不到 Test::TestController 的操作“foo”
测试文件夹中的 controller 文件:
class Test::TestController < ApplicationController
class << self
def index
render json: {test:"Hello World!"}
end
def foo
render json: {response:"It works!"}
end
end
end
路线文件:
Rails.application.routes.draw do
namespace 'test' do
resources :test
end
get '/:id', to: 'test/test#foo'
end
这是不可能的。 它甚至不是一个好主意。
Rails 控制器以请求和环境的形式接受输入,其中包括服务器设置和中间件作为初始化程序 arguments 塞进的任何内容。 它们不是全局变量,例如 PHP。
controller 本身的动作实际上并没有采取任何 arguments。 因此,即使您可以将您的操作声明为 class 方法,您也绝对没有上下文。 它实际上非常无关紧要,因为您必须更换整个路由器层才能调用它。
Ruby 甚至没有真正的 singleton 类。 如果您想要一个无法实例化的 object,请使用模块(不,您不能将模块设为导轨中的 controller)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.