I have created a new class in my Rails application under a folder structure of app/datatables
我在app / datatables的文件夹结构下的Rails应用程序中创建了一个新类
The class is saved in a file in this directory and it is saved as DatasetIndexDatatable.rb
该类保存在此目录的文件中,并保存为DatasetIndexDatatable.rb
The contents of the class file is as follows:
类文件的内容如下:
class DatasetIndexDatatable
delegate :params, :h, :link_to, :number_to_currency, to: :@view
def initialize(view)
@view = view
end
end
When I try to instantiate this class from a controller in my application, Rails gives an error:
当我尝试从我的应用程序中的控制器实例化此类时,Rails给出错误:
uninitialized constant DatadescriptionController::DatasetIndexDatatable
The code in the controller which attempts to instantiate the new class is as follows:
控制器中尝试实例化新类的代码如下:
class DatadescriptionController < ApplicationController
layout "datadescription"
def index
respond_to do |format|
format.html
format.json { render json: DatasetIndexDatatable.new(view_context) }
end
end
end
Why can't Rails see the new class? I have tried adding the folder containing the class to the config.autoload_paths variable in application.rb:
为什么Rails不能看到新类?我尝试将包含该类的文件夹添加到application.rb中的config.autoload_paths变量中:
config.autoload_paths += %W(#{config.root}/lib
#{config.root}/datatables)
but the same error occurs. I have also tried instantiating the new class in the controller using the global namespace:
但是会发生同样的错误。我还尝试使用全局命名空间在控制器中实例化新类:
format.json { render json: ::DatasetIndexDatatable.new(view_context) }
and using the containing folder for the class as a namespace:
并使用类的包含文件夹作为命名空间:
format.json { render json: Datatables::DatasetIndexDatatable.new(view_context) }
all to no avail. What am I doing wrong?
一切都无济于事。我究竟做错了什么?
1 个解决方案
#1
13
The file is named incorrectly. Instead of:
该文件名称不正确。代替:
DatasetIndexDatatable.rb
Call it:
叫它:
dataset_index_datatable.rb
This is a Rails standard naming convention. If you define a CamelCase
class, the file that contains the definition should be named camel_case.rb
which is lower case with underscores.
这是Rails标准命名约定。如果定义了CamelCase类,则包含该定义的文件应命名为camel_case.rb,它是带下划线的小写。
#1
13
The file is named incorrectly. Instead of:
该文件名称不正确。代替:
DatasetIndexDatatable.rb
Call it:
叫它:
dataset_index_datatable.rb
This is a Rails standard naming convention. If you define a CamelCase
class, the file that contains the definition should be named camel_case.rb
which is lower case with underscores.
这是Rails标准命名约定。如果定义了CamelCase类,则包含该定义的文件应命名为camel_case.rb,它是带下划线的小写。