Register now and start sharing your code snippets.
-->

How to backup ActiveRecord model data to YAML with ar_fixtures

Ruby posted 2 months 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 5 months 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

How to use named_scope in Rails

Ruby posted 5 months ago by christian

Simple example of how to use the named_scope feature:

   1  class Feed < ActiveRecord::Base
   2   
   3    named_scope :active, :conditions => "(active = 1)"
   4    named_scope :stale,  :conditions => ["last_updated > ?", 30.minutes.ago.to_s(:db)]

Usage:

   1  Feed.active # return the active feeds

Chaining is also possible:

   1  Feed.active.stale # return the feeds that need to be updated

Tagged named_scope, rails, activerecord, ruby