How to get ActiveRecord and Rails to print SQL to the production log

Ruby posted about 1 month ago by christian

Add to the end of config/environment.rb:

   1  ActiveRecord::Base.logger.level = Logger::DEBUG

Config/environments/production.rb might also work.

Tagged sql, production, activerecord, rails, logging

How to customize to_json

Ruby posted 5 months ago by christian

   1  def to_json(options = {})
   2    if options.empty?
   3      super :only => [:id, :name]
   4    else
   5      super options
   6    end
   7  end
   8  

Now post.to_json will only include the id and name attributes.

Note that for arrays of objects—at least with Rails 2.3.4—you need use the same parameters on the array.to_json method:

   1  Post.all.to_json :only => [:id, :name]

Tagged to_json, activerecord, rails

How to run ActiveRecord migrations from the console

Ruby posted about 1 year ago by christian

There are multiple ways of running migrations from the console. This might be the easiest one to remember:

   1  irb ActiveRecord::Schema
   2  add_index :followers, [:leader_id, :follower_id], :unique => true

Tagged activerecord, console, migrations, schema

How to backup ActiveRecord model data to YAML with ar_fixtures

Ruby posted about 1 year ago by christian

First install the plugin:

   1  script/plugin install http://github.com/mileszs/ar_fixtures/commits/master 

Then dump data for all models with:

   1  rake db:data:dump:all

There’s a task for loading the data into the database, see rake -T for more information.

Tagged fixtures, backup, activerecord, rails, yaml

How to use ActiveRecord without Rails

Ruby posted about 1 year ago by christian

This is an example of how to use ActiveRecord without Rails:

   1  ['/model', '/db'].each do |folder|
   2    $:.unshift File.dirname(__FILE__) + folder
   3  end
   4  
   5  require 'test/unit'
   6  require 'rubygems'
   7  require 'activerecord'
   8  
   9  ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + '/debug.log')
  10  ActiveRecord::Base.configurations = YAML::load(IO.read(File.dirname(__FILE__) + '/config/database.yml'))
  11  ActiveRecord::Base.establish_connection('sqlite3')
  12  
  13  require 'schema'
  14  

Schema contains, for example:

   1  ActiveRecord::Schema.define :version => 0 do
   2    create_table :languages, :force => true do |t|
   3      t.string :name
   4    end
   5  end

Tagged activerecord, standalone, rails, ruby