Seed Data onto Database in an ruby program using activerecord - ruby

How can I seed some data to an table using active record in an standalone ruby program?
So far my code is:
require 'prawn'
require 'active_record'
require 'pg'
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: 'localhost',
database: 'sample',
username: 'postgres',
password: '...'
)
ActiveRecord::Schema.define do
create_table :xmldata, force: true do |t|
t.text :xmlstr
end
end

Make sure you create table only if it does not exist:
ActiveRecord::Schema.define do
if not connection.table_exists? :xmldata
create_table :xmldata, force: true do |t|
t.text :xmlstr
end
end
end
end
Create an ActiveRecord model for the table.
class Xmldata < ActiveRecord::Base
end
Create objects and save them
Xmldata.create({xmlstr: "<person><name>SOuser</name></person>"})

Related

how do I read from a Database in ruby sinatra using active record

I want to read entrys from a Database using active_record and keep getting diffrent Errors like: Name error and can't find the database or it can't execute the query.
so my question here is how do i read from a database or execute SQL-queries and for example write the result into a variable?
require 'rubygems'
require 'sinatra'
require 'active_record'
require 'sqlite3'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "test.db"
)
class Article < ActiveRecord::Base
end
#ActiveRecord::Migration.create_table :users do |t|
# t.string :name
#end
class App < Sinatra::Application
end
get '/' do
output = users.select(:all)
f = File.open('name','a'); f.write(output); f.close
#puts User.first
To read the data from the users table, you'd simply do:
class User < ActiveRecord::Base
end
get '/' do
#users = User.all
puts "Grabbed #{#users.size} user(s) from database"
end

How to pass ec2 instances details to sqlite db using ruby?

I have the following code:
require 'rubygems'
require 'aws-sdk'
require 'sqlite3'
require 'active_record'
db = SQLite3::Database.new('awsec2.db')
ActiveRecord::Base.establish_connection(
:adapter=> "sqlite3",
:database=> "awsec2")
ActiveRecord::Schema.define do
create_table :instances do |t|
t.column :instance_id, :string
t.column :status, :string
end
end
ACCESS_KEY_ID = '.......................'
SECRET_ACCESS_KEY = '....................'
ec2 = AWS::EC2.new(:access_key_id => ACCESS_KEY_ID, :secret_access_key => SECRET_ACCESS_KEY)
ec2.instances.inject({}) { |m, i| m[i.id] = i.status; m } # How to pass those items to the instances table
How to store the data collected by ec2.instances methode to the database table?
Here is metadata query tool made by amazon. It is just a helper script to fetch data from metadata url.

Tests within Gem need to test migration generator and apply migrations for tests

I'm working on a Gem that contains a migration generator and a bunch of models, classes, etc that utilize the tables created as part of the migration.
Although testing the migration generator itself is easy enough - there's loads of tutorials around for getting that done, what i'm trying to work out is how to actually run the migration on the test DB so I can later test how the gem interacts with the test data?
Since the gem doesn't have a schema.rb, I wasn't sure how to go about doing it.
This is how I run migrations in code;
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Migration.verbose = false
#migration = Class.new(ActiveRecord::Migration) do
def change
create_table :users, :force => true do |t|
t.string :roles_mask
end
create_table :user_without_roles, :force => true do |t|
t.string :roles_mask
end
create_table :user_without_role_masks, :force => true do |t|
end
end
end
#migration.new.migrate(:up)
If you have a string containing your generated migration you could do something like this in your test setup;
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Migration.verbose = false
# Or however you intend to grab the output of the migration generator
migration_string = ERB.new(File.read(<file name here>)).result
migration = Class.new(ActiveRecord::Migration)
migration.class_eval(migration_string)
migration.new.migrate(:up)
That should give you a migrated database using the migration you've generated.
You can do something like this:
I am going to assume you're using ActiveRecord. So in your test helper you should setup a in-memory database:
require 'active_record'
# Connection must be establised before anything else
ActiveRecord::Base.establish_connection(
:adapter => defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3',
:database => ':memory:'
)
Then invoke the rake task within your test. This would look something like:
require 'rake'
requie File.expand_path('../Rakefile', __FILE__) # you'll need to modify this path to actually point to the Rakefile
Rake::Task['db:migrate'].invoke
The rake taks invocation is untested, but that should point you in the right direction.
The other option would be to just run the command:
%x{rake db:migrate}

ActiveRecord and sqlite3 : find does not accept any condition?

I have a problem I can't figure out here. I'm writing a ruby script that deals with an sqllite database.
require 'rubygems'
require 'sqlite3'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "../database/my.db"
)
class KeyWord < ActiveRecord::Base
set_table_name "keywords"
end
# THIS STATEMENT WORKS (finds the first record, returns "ruby") :
KeyWord.find(1).keyval
# THOSE STATEMENTS RETURN NO RESULT :
KeyWord.find(:all, :conditions => {:keyval => "ruby"})
KeyWord.find_by_sql("SELECT * FROM keywords WHERE keyval='ruby'")
KeyWord.find_by_keyval("ruby")
This is how the table was created :
create_table :keywords do |table|
table.column :keyval, :text
end
Does anyone know where this could come from ?
Thanks,
R.
I see a couple of issues here.
I'm not sure why you're manually setting your table name.
ActiveRecord assumes that your model name is camelCased. So... AR
would, by default, search for a table called key_words. Why not just
go with that?
Pay attention to which version of active record you are
using. Passing in conditions is deprecated. You should be using the
.where syntax. So... you would need to do KeyWord.where(:keyval
=> 'ruby').first or end in .all for a collection of results.
If you are just fooling around, you can use sqlite3 in memory.
ActiveRecord::Base.establish_connection( adapter: 'sqlite3',
database: ":memory:")
Also don't forget to define your schema!
Here is full code w/ more modern syntax.
require 'rubygems'
require 'sqlite3'
require 'active_record'
ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ":memory:" )
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define(version: 2) do
create_table :key_words do |t|
t.text :keyval
end
end
class KeyWord < ActiveRecord::Base
end
Keyword.create!(:keyval => 'ruby')
# THESE STATEMENTS WORK:
KeyWord.find(1).keyval
KeyWord.where(:keyval => 'ruby').first
KeyWord.where(:keyval => 'ruby').all
KeyWord.find_by_sql("SELECT * FROM key_words WHERE keyval='ruby'")
KeyWord.find_by_keyval("ruby")

ActiveRecord::Migration - Referencing a table in another schema

I'm using Ruby and PostgreSQL and have created 3 distinct DB schemas: billing (for billing related data), customer (for customer related data) and edocs (for electronic documents related data).
I'm not using Rails so I have a stand-alone migration code like this:
#migrate.rb
if ARGV[0] =~ /VERSION=\d+/
version = ARGV[0].split('=')[1].to_i
else
version = nil
end
ActiveRecord::Base.default_timezone = :utc
#logger = Logger.new $stderr
ActiveRecord::Base.logger = #logger
ActiveSupport::LogSubscriber.colorize_logging = false
#config = YAML.load_file(File.join(File.dirname(__FILE__), 'database.yml'))
ActiveRecord::Base.establish_connection(#config["edocs"])
ActiveRecord::Migrator.migrate(".", version)
I have already realized that I probably have to create a different directories to contain the migration for the different schemas, and changing connection info for each migrate.rb.
But I'm not sure how I'm going to make a table reference another table that is in another schema.
For example:
class CreateBillingEventsTable < ActiveRecord::Migration
def self.up
create_table :billing_events do |t|
t.references :customer, :null => false
t.references :service_type, :null => false
t.timestamps
end
change_table :billing_events do |t|
t.index [:customer_id, :created_at]
end
end
def self.down
remove_index :billing_events, :column => [:customer_id, :created_at]
drop_table :billing_events
end
end
In the above example, "customer" and "billing_events" are in different schemas.
How can I code that?
Thanks.

Resources