从控制器而不是通过控制台调用方法时出现 "uninitialized constant" 错误

Getting an "uninitialized constant" error when method is called from controller, but not through console

[Rails4]你好。我正在创建一个网络应用程序。这是 Rails 4。另外,这个项目没有使用 ActiveRelations 或数据库。然而,它正在使用一个预先存在的 M$_SQL 数据库,我使用 gem 查询它,我发现它叫做 tiny_tds.

我遇到了一个错误,我一直很纠结。

基本上,我的模型是 "Network" class,看起来像这样:

app/models/network.rb

class Network

include Query #THIS IS MY CONCERN MODULE (SHOWN BELOW)

include ActiveModel::Conversion
include ActiveModel::Validations
extend  ActiveModel::Naming

...

def initialize()
    @technology = "CDMA"
    @sites      = []
end

...

def get_sites()
    #Custom query - this calls the Query Module
    @sites = Query.query_avg(@technology, @s_range, @e_range)

end

...

end

此 class 调用我创建并卡在 /concerns 文件夹中的模块。它依赖于 "tiny_tds" gem,这是一个用于查询 M$_SQL 数据库的 gem。在我尝试将它与 rails:

集成之前,它一直运行良好

app/models/concerns/query.rb

module Query

extend ActiveSupport::Concern

def self.query_avg(tech, s_date, e_date)

    q_string = "..." #custom sql string (omitted for brevity)

    return execute(q_string) #return to calling class

end

private

    def self.execute(sql)

        #This is a TinyTds Specific command (where error is seen)
        client = TinyTds::Client.new(username: '...', password: '...', host: 'x.x.x.x')
        result = client.execute(sql)
        results = result.each(:symbolize_keys => true, :as => :array, :cache_rows => true, :empty_sets => true) do |rowset| end

        return results
    end

end

最后但同样重要的是,这里是调用代码的控制器:

app/controllers/networks_controller.rb

class NetworksController < ApplicationController
  def new
    @network = Network.new
    d1 = Date.new(2014,11,22)
    d2 = Date.new(2014,11,30)
    @network.date_range(d1,d2)
    @network.get_sites
end

现在...当我加载 "rails console" 并在那里手动输入时,上面的代码(在控制器中)运行良好。所有的数据都是我想要的

但是,当我尝试调用 http://localhost:3000/networks/new(即使视图为空)时,我在浏览器中收到以下错误:

uninitialized constant Query::TinyTds

...(inside the query.rb module listed above)...

client = TinyTds::Client.new(username: '...', password: '...', host: 'x.x.x.x')

PS。我随机安装 bundle install 并验证 tiny_tds gem 已安装。

感谢所有帮助,谢谢!

添加新的gem后,您总是需要重新启动服务器。 Gem 在应用程序启动时加载,不是自动加载的对象。