2014-01-31 65 views
0

我已經寫了一個rake任務來更新我正在使用模型執行的數據庫。我呼籲模式的功能我rake任務裏面是這樣的:ActiveRecord :: ConnectionNotEstablished錯誤

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 
+0

看起來它無法連接 - 你有本地主機上的MYSQL設置? –

+0

是的,我在本地主機上設置了MYSQL設置。 – Joy

+0

當您調用查詢時它正在運行嗎? –

回答

0

在軌,對於MySQL服務器在一個MySQL和mysql2寶石兩種不同的適配器。檢查你的gemfile中是否有mysql gem。如果沒有,然後打開rails控制檯,然後輸入ActiveRecord :: Base.establish_connection(「mysql:// your_username:yourpassword @ localhost/yourdatabasename」)。你有沒有配置你的MySQL服務器。你在所有環境中都遇到錯誤嗎?通過使用命令'mysql -u USERNAME -p'登錄到mysql服務器來檢查它的默認根和沒有密碼。

相關問題