The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Easy ActiveRecord Scripts

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Jamis Buck

Posts: 184
Nickname: minam
Registered: Oct, 2004

Jamis Buck is a C/Java software developer for BYU, and hacks in Ruby for fun.
Easy ActiveRecord Scripts Posted: Oct 3, 2005 2:27 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Jamis Buck.
Original Post: Easy ActiveRecord Scripts
Feed Title: the buckblogs here
Feed URL: http://weblog.jamisbuck.org/blog.cgi/programming/index.rss
Feed Description: Jamis Buck's corner of the blogging universe. Mostly about ruby, but includes ramblings on a variety of topics.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Jamis Buck
Latest Posts From the buckblogs here

Advertisement

ActiveRecord (the ORM component of Rails) is really a pretty slick little piece of equipment. Not only does it integrate seamlessly with the other parts of the Rails stack, it can be easily used on its own. I do so frequently when trying to duplicate reported bugs. Consider the following little script:

  require 'active_record'

  ActiveRecord::Base.logger = Logger.new(STDERR)
  ActiveRecord::Base.colorize_logging = false

  ActiveRecord::Base.establish_connection(
    :adapter => "sqlite",
    :dbfile  => ":memory:" 
  )

  ActiveRecord::Schema.define do
    create_table :foxes do |t|
      t.column :name, :string
    end

    create_table :trucks do |t|
      t.column :fox_id, :integer
      t.column :color, :string
    end
  end

  class Fox < ActiveRecord::Base
    has_many :trucks
  end

  class Truck < ActiveRecord::Base
    belongs_to :fox
  end

  fox = Fox.create :name => "Small" 
  fox.trucks.create :color => "Blue" 
  fox.trucks.create :color => "Orange" 

  puts Fox.find(1).trucks.length

The above script uses an in-memory SQLite database, so it doesn’t leave any messes around on disk. It also logs to STDERR, so I can see all the SQL that is produced, and it turns off colorized logging (because I prefer a white-background terminal and AR’s colors aren’t very friendly to that). It then defines the tables using ActiveRecord::Schema, defines the classes, adds some data, and then manipulates the data.

Nice and simple! (Note that ActiveRecord::Schema is only available in the beta gems, currently, but everything else should work with the released version of AR.)

Read: Easy ActiveRecord Scripts

Topic: Multilingual Rails Update Previous Topic   Next Topic Topic: Shipped ~4,700 Rails books this week

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use