Does Ruby or Rails have an equivalent of pandas.read_sql? - ruby-on-rails

So in Python, I am used to using something like
pd.read_sql(sql_query, connection_object)
in order to grab data from a remote database. But when forming a similar connection object in Ruby:
require 'pg'
#connect_obj = PG.connect(:host => host, :dbname => db , :user => user , :password => pwd , :port => port )
what can Ruby do in order to run something like pd.read_sql(sql_query, connection_object)?

With Rails, the usual way is to create a model class for your table and then use ActiveRecord methods.
But if you want to run some general queries without using any model classes, you can try it this way:
ActiveRecord::Base.connection.execute('SELECT * FROM users').each { |row| puts row }

Related

Extracting PDF rows to Rails db?

My source contains only 1,500 objects. At most it may grow to 2,000. I'm obtaining the objects via PDF and parsing with PDF Reader. They are parsed and returned by rows as String objects:
file = File.open("app/assets/images/file.pdf")
reader = PDF::Reader.new(file)
page = reader.pages[0]
rows = page.text.scan(/^.+/) #String Objects
rows.slice!(0..3) #Removes Header Info
Sample object :
=> ["1", "3", "215", "06/02/83", "Law,", "Steve"]
Then I remove the "," appended to last name and split the String object thus creating a Array Object:
row = #rows[0].tr(',', '').split #Array Objects
=> ["1", "3", "215", "06/02/83", "Law", "Steve"] #Array Object
I want to iterate through each row and insert into User table via console or form. What methods should I consider?
Thanks!
Lets assume you have mysql with users table in it and active_record gem installed.
If you writing just plain ruby script first you need to require active_record(commonly used ORM in rails), establish connection to db and create User model to get access to the users table via ActiveRecord:
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => 'mysql',
:host => 'localhost',
:database => 'your_db_name'
)
class User < ActiveRecord::Base
end
So now all you need to do is to iterate over the rows and call User.create method:
rows.slice!(0..3).each do |row|
row.reverse! # reverse array so we can easily access its elements with ruby Array methods
first_name = row.first
last_name = row.second.sub(/,/, '') # remove ',' symbol
birth_date = row.third
...
User.create(:first_name => first_name, :last_name => last_name, :birth_date => birth_date, ...) # I assumed you have first_name, last_name, ..., columns in your users table
end
Its all can be done in one file.
If you writing something like a rake task in your Rails environment you need to configure db connection in config/database.yml and create User model in app/models dir.

Have access to multiple databases [duplicate]

In our program, each customer gets their own database. We e-mail them a link that connects them to their database. The link contains a GUID that lets the program know which database to connect to.
How do I dynamically and programatically connect ActiveRecord to the right db?
You can also do this easily without hardcoding anything and run migrations automatically:
customer = CustomerModel.find(id)
spec = CustomerModel.configurations[RAILS_ENV]
new_spec = spec.clone
new_spec["database"] = customer.database_name
ActiveRecord::Base.establish_connection(new_spec)
ActiveRecord::Migrator.migrate("db/migrate_data/", nil)
I find it useful to re-establish the old connection on a particular model afterwards:
CustomerModel.establish_connection(spec)
you can change the connection to ActiveRecord at any time by calling ActiveRecord::Base.establish_connection(...)
IE:
ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev",
:username => "root", :password => "password" })
It's been a while since this question has been created, but I have to say that there is another way too:
conn_config = ActiveRecord::Base.connection_config
conn_config[:database] = new_database
ActiveRecord::Base.establish_connection conn_config
class Database
def self.development!
ActiveRecord::Base.establish_connection(:development)
end
def self.production!
ActiveRecord::Base.establish_connection(ENV['PRODUCTION_DATABASE'])
end
def self.staging!
ActiveRecord::Base.establish_connection(ENV['STAGING_DATABASE'])
end
end
And in .env (with dotenv-rails gem for instance):
PRODUCTION_DATABASE=postgres://...
STAGING_DATABASE=postgres://...
And now you can:
Database.development!
User.count
Database.production!
User.count
Database.staging!
User.count
# etc.

How do you call "contains?" on a MongoMapper Array in Rails 3?

I want to know how to check if an array element exists inside of a MongoMapper Array. This question is the closest I could find, but it addresses queries rather than simply using a document you already have.
My User model contains the line
key :roles, Array
The 'roles' array contains strings such as 'admin' or 'user.' For authorization, I need to call something like the following method on an instance of User:
if user.roles.contains?('admin')
# Do administrative stuff.
end
But when I try to call 'contains?' Ruby complains that there is no such method:
NoMethodError (undefined method `contains?' for #<Array:0x007fc845cd8948>):
app/models/ability.rb:11:in `initialize'
app/controllers/settings_controller.rb:5:in `index'
If there's no way to do this, then how do I convert the Array into a Ruby array to call 'contains?'? Calling to_a isn't doing it:
if user.roles.to_a.contains?('admin') # etc...
I'm using Rails 3.2.13, Ruby-1.9.3-p392, and MongoMapper 0.12.0 on Mountain Lion.
the function you are looking for is include?, so the expression would be: user.roles.include?('admin')
However since you mentioned mongomapper, if you were preforming a query on the roles array you would do the fallowing:
User.where( :roles => 'admin' )
You can also search an array with an array
User.where( :roles.in => ['admin'] )
for a query with admin or user you can do:
User.where( :$or => [{:roles => 'admin'},{:roles => 'user'}] )
and you can do and just the same:
User.where( :$and => [{:roles => 'admin'},{:roles => 'user'}] )

Mr. Ruby, Ms Rails, my json created record is empty

this newbie here is smacking his head with webservices over Rails.
Perhaps someone could ease my pain?
I've created a simple rails app, and generated the scaffold MyRecords. Then I'm trying to create a record over irb with the code below :
testWS.rb
require 'HTTParty'
class MyRecordCreate
include HTTParty
base_uri 'localhost:3000'
def initialize(u, p)
#auth = {:username => u, :password => p}
end
def post(text)
options = { :body => { name:text} }
self.class.post('/my_records', options)
end
end
response = HTTParty.get("http://localhost:3000/my_records/new.json")
print response
record = MyRecordCreate.new("","").post("test remote record")
print record
With the code above, I managed to create a record. the thing is that my Record (which only has the column "name") is created with an empty name!
Any suggestions on this one?
I'm longing to slice this despair piece by piece.
Thank you for your contribute.
Try adding these two lines to your HTTParty class:
format :json
headers "Accept" => "application/json"
These tell httparty and the remote service to which it connects to send and receive JSON. For your example (with .json at the end of the URL) it isn't necessary to add the second line, but I find it is good practice and keep it anyway.
The next problem is that Rails expects your uploaded data to be inside the top level name of your object. So, for your example, the options line should look something like:
options = { :body => { :person => { :name => text } } }
Replace person with the name of the model that you are attempting to create.

How can I dynamically change the Active Record database for all models in Ruby on Rails?

In our program, each customer gets their own database. We e-mail them a link that connects them to their database. The link contains a GUID that lets the program know which database to connect to.
How do I dynamically and programatically connect ActiveRecord to the right db?
You can also do this easily without hardcoding anything and run migrations automatically:
customer = CustomerModel.find(id)
spec = CustomerModel.configurations[RAILS_ENV]
new_spec = spec.clone
new_spec["database"] = customer.database_name
ActiveRecord::Base.establish_connection(new_spec)
ActiveRecord::Migrator.migrate("db/migrate_data/", nil)
I find it useful to re-establish the old connection on a particular model afterwards:
CustomerModel.establish_connection(spec)
you can change the connection to ActiveRecord at any time by calling ActiveRecord::Base.establish_connection(...)
IE:
ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev",
:username => "root", :password => "password" })
It's been a while since this question has been created, but I have to say that there is another way too:
conn_config = ActiveRecord::Base.connection_config
conn_config[:database] = new_database
ActiveRecord::Base.establish_connection conn_config
class Database
def self.development!
ActiveRecord::Base.establish_connection(:development)
end
def self.production!
ActiveRecord::Base.establish_connection(ENV['PRODUCTION_DATABASE'])
end
def self.staging!
ActiveRecord::Base.establish_connection(ENV['STAGING_DATABASE'])
end
end
And in .env (with dotenv-rails gem for instance):
PRODUCTION_DATABASE=postgres://...
STAGING_DATABASE=postgres://...
And now you can:
Database.development!
User.count
Database.production!
User.count
Database.staging!
User.count
# etc.

Resources