Ruby on rails ActiveRecord::ConnectionNotEstablished错误

Ruby on rails ActiveRecord::ConnectionNotEstablished错误,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我已经编写了一个rake任务来更新我的数据库,我正在通过一个模型来完成这个任务。我在rake任务中调用了model函数,如下所示: get_first_student = Student.get_first_id 我写了如下的模范学生: class Students < ActiveRecord::Base attr_accessible :id, :roll_num :name, :class self.table_name = 'students' if Rails.env ==

我已经编写了一个rake任务来更新我的数据库,我正在通过一个模型来完成这个任务。我在rake任务中调用了model函数,如下所示:

 get_first_student = Student.get_first_id
我写了如下的模范学生:

class Students < ActiveRecord::Base
attr_accessible :id, :roll_num :name, :class
self.table_name = 'students'

if Rails.env == "development"
  CONN1 = establish_connection :adapter => "mysql2",
        :database => "mydb_dev",
        :username => "root",
        :password => "" ,
        :host => "localhost"

  CONN2 = establish_connection :adapter => "mysql2",
        :database => "mydb2_dev",
        :username => "root",
        :password => "",
        :host => "1.2.3.4"
 else
  CONN1 = establish_connection :adapter => "mysql2",
        :database => "mydb_prod",
        :username => "root",
        :password => "" ,
        :host => "localhost" 

  CONN2 = establish_connection :adapter => "mysql2",
        :database => "mydb2_prod",
        :username => "root",
        :password => "" ,
        :host => "localhost"
 end

 def self.get_first_id
   p "****"
   p CONN1
   p "****"
   sql = %Q{SELECT MIN(id) FROM mydb.students;}
   first_student_id = CONN1.connection.execute(sql).first[0]
   return first_student_id
 end
运行后,我得到以下输出:

 #<ActiveRecord::ConnectionAdapters::ConnectionPool:0x007f948c223120 @mon_owner=nil,     
 @mon_count=0, @mon_mutex=#<Mutex:0x007f948c2230d0>, @spec=#    
 <ActiveRecord::Base::ConnectionSpecification:0x007f948c2232d8 @config=
{:adapter=>"mysql2",:database=>"mydb_dev", :username=>"root", :password=>"", 
:host=>"localhost"}, @adapter_method="mysql2_connection">, @reserved_connections={}, 
@queue=#<MonitorMixin::ConditionVariable:0x007f948c223080 @monitor=#
<ActiveRecord::ConnectionAdapters::ConnectionPool:0x007f948c223120 ...>, @cond=#
<ConditionVariable:0x007f948c223058 @waiters=[], @waiters_mutex=#
<Mutex:0x007f948c223008>>>, @timeout=5, @size=5, @connections=[], 
@automatic_reconnect=false>

ActiveRecord::ConnectionNotEstablished

在rails中,mysql服务器有两个不同的适配器,一个在mysql中,另一个在mysql2中。检查gem文件中是否有mysql gem。如果不是,则打开rails控制台,并键入ActiveRecord::Base.build\u connectionmysql://your_username:yourpassword@localhost/yourdatabasename。您是否配置了mysql服务器。您是否在所有环境中都遇到错误?。通过使用命令“mysql-u USERNAME-p”登录到mysql服务器进行检查,默认情况下,该命令是其根,不带密码

第二次调用“建立连接”时,您创建了第一个池,这就是您尝试使用的CONN1


尽管此方法返回可以捕获和使用的ConnectionPool对象,但值得避免。ActiveRecord管理连接池,除非您明确表示不同,否则将假定您只希望其中一个处于活动状态。最近他们添加了一些。

看起来它无法连接-您的本地主机上有MYSQL设置吗?是的,我在本地主机上设置了MYSQL设置。调用查询时它正在运行吗?不,它没有运行。应该尝试运行它!