Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Ben Marini

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Getting ActiveRecord to auto reconnect after lost connection

I puts this code in a file called active_record_hacks.rb in config/initializers but it could easily be a plugin.

   1  
   2  ActiveRecord::ConnectionAdapters::MysqlAdapter.module_eval do
   3    def execute_with_retry_once(sql, name = nil)
   4      retried = false
   5      begin
   6        execute_without_retry_once(sql, name)
   7      rescue ActiveRecord::StatementInvalid => exception
   8        ActiveRecord::Base.logger.info "#{exception}, retried? #{retried}"
   9  
  10        # Our database connection has gone away, reconnect and retry this method
  11        reconnect!
  12        unless retried
  13          retried = true
  14          retry
  15        end
  16      end
  17    end
  18  
  19    alias_method_chain :execute, :retry_once
  20  end

Manually Pulling Data From MySQL in Rails

Sometimes you just have to do it yourself, like when you have relationships between different databases.
Here I wanted to retrieve an array of site_ids:

   1  
   2      result = ActiveRecord::Base.connection.execute("SELECT * FROM sites_users WHERE user_id ='#{self.id}'")
   3      rows = []
   4      result.each_hash {|h| rows << h['site_id'].to_i }
   5      return rows


UPDATE: ( An easier, better way)

   1  
   2      rows = ActiveRecord::Base.connection.select_values("SELECT site_id FROM sites_users WHERE user_id ='#{self.id}'")
   3      return rows.map {|el| el.to_i }


There is also:

select_one(sql, name = nil)
select_value(sql, name = nil)
select_all(sql, name = nil)

Deploying to different locations with Capistrano

// description of your code here
In your deploy.rb file:

   1  
   2  if ENV["SERVER"] && ENV["SERVER"] == "production"
   3    set :primary_server, "production.com"
   4    set :user, "ben"
   5  elsif ENV["SERVER"] && ENV["SERVER"] == "staging"
   6    set :primary_server, "staging.local"
   7    set :user, "ben"
   8  else
   9   ...
  10  end
  11  
  12  role :web, primary_server
  13  role :app, primary_server
  14  role :db,  primary_server, :primary => true
  15  


The you say:
rake deploy SERVER=staging
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS