Sunday, March 6, 2011

Add records from external ruby script

What is the best way to add records to a database from an external script. I would like to use activerecord but I'm not sure how to do so outside the rails directory structure.

From stackoverflow
  • You can use activerecord in ruby. Assuming you have installed the required database driveer. you can do something similar to

    require 'activerecord'
    
    ActiveRecord::Base.establish_connection(
      :adapter => 'your_database_adapter',
      :host => 'your_host',
      :username => 'username'
      :password => 'password',
      :port => 'port_number'
    )
    

    to establish a database connection. Since you want to add records to the database, I assume the schema is already present. Then you simply do

    class ModelName < ActiveRecord::Base
      has_many :modelz
    end
    
    class Modelz < ActiveRecord::Base
      belongs_to :model_name
    end
    

    And you are set. (Thats right, you can do everything that you can do in rails using active record once you establish database connection, even have relationships between models) You can do whatever you want with the object of the model class you just created. Like,

    ModelName.find(:all)
    
    @model = ModelName.new
    @model.user_id = rand(10)
    @model.save
    

    etc etc.

    If you don't have a schema in place, don't panic. You can create it by embedding code simlar to following after establishing database connection.

    ActiveRecord::Schema.define do
      create_table :sometable do |table|
        table.integer :int1, :int2
        table.string :str1, :str2
      end
    
      create_table :yetanothertable do |table|
        table.integer :anotherint
        table.text :sometext
      end
    end
    

    This should work fine. The code given here is a sample and may not be syntactically perfect. This should also help. However, the schema definition is done the older rails way.

0 comments:

Post a Comment