How to get ActiveRecord and Rails to print SQL to the production log
Add to the end of config/environment.rb:
1 ActiveRecord::Base.logger.level = Logger::DEBUG
Config/environments/production.rb might also work.
How to customize to_json
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]
How to run ActiveRecord migrations from the console
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
How to backup ActiveRecord model data to YAML with ar_fixtures
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.
How to use ActiveRecord without Rails
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