Topic: Create a single rb file that does ActiveRecord without rails

Hello,

I'm just learning Ruby and Rails.  It is simply wonderful.  But I was wondering if it is possible to create just a ruby file that does some ActiveRecord db stuff, without running in the context of rails. 

I've seen examples on how to do this via a ruby script, however, I'm wondering how to do it via the web.  Kind of like creating a single php script and copying it to a web server.

Thanks.

Re: Create a single rb file that does ActiveRecord without rails

To do it on the web you'd have to run Ruby as a CGI script. It's possible and would work very similar to PHP/Perl scripts.

To use AR in a Ruby script, just make sure it's installed and require it, like so:

require 'active_record'

#DB config
config = {
  :adapter => 'mysql',
  :host => 'localhost',
  :database => 'web',
  :user => 'john',
  :password => 'what',
  :port => 3306
}
#establish connection
ActiveRecord::Base.establish_connection(config)

#write some AR classes
class Post < ActiveRecord::Base
  validates_presence_of :title, :body
end

#use your classes down here
@posts = Post.find(:all, :order => 'created_at DESC')
@posts.each do |post|
#do your thing with each post here
end


Fair word of warning though: this will be less maintainable if/when your project grows beyond the scope of 1-2 scripts.

vinnie - rails forum admin