Connecting to a separate mysql database in Rails - mysql

I am trying to connect to a separate mysql database than what my rails app is on. I am trying to connect to a database of guitar tabs so that users can search for specific songs.
I have my database.yml configured to:
tabs:
adapter: mysql2
encoding: utf8
database: (dbname)
username: (username)
password: (pass)
host: hostname.rds.amazonaws.com
port: 3306
So far I have tab.rb as my model:
class Tab < ActiveRecord::Base
self.abstract_class = true
establish_connection ('tabs')
end
finally, my controller
class TabController < ApplicationController
def listTabs
#tabs = Tabs.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #tabs }
end
end
def showTabs
#tabs = Tabs.find_by_sql "SELECT * FROM gp"
respond_to do |format|
format.html # index.html.erb
format.json { render json: #statuses }
end
end
end
I'm new to rails and I really want to get this to work. If you are able to help me just run the query "SELECT * From gp" and display it in my view, I will love you forever.
Thanks for your help!

in your model the name is Tab and you use in controller Tabs i.e is wrong, please use Tab.all or Tab.find_by_sql

Related

ActiveRecord MySQL Lost connection to MySQL server during query

I'm having an issue connecting to an external AWS Aurora MySQL in my Rails app in production.
Here is the setup:
One main PostgreSQL database for the app
One external (AWS Aurora MySQL) database used as a reader for huge datasets
In development, everything works fine, but when I deploy to Heroku, I can only successfully query one table of the external database. When I create another table I get this error message:
ActionView::Template::Error (Mysql2::Error::ConnectionError: Lost connection
to MySQL server during query: SELECT `TMC_Identification`.`direction`,
`TMC_Identification`.`miles`, `TMC_Identification`.`road`,
`TMC_Identification`.`tmc` FROM `TMC_Identification`) :
1: <%= raw(#tmcs.to_json) %>
Rails 5.2
Ruby 2.5.3
Models:
class TmcReading < ApplicationRecord
establish_connection(:tmc_data)
self.table_name = "TMC_Readings"
end
class TmcIdentification < ApplicationRecord
establish_connection(:tmc_data)
self.table_name = "TMC_Identification"
end
database.yml:
default: &default
adapter: postgresql
encoding: unicode
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
production:
<<: *default
database: production
username: admin
password: <%= ENV['DATABASE_PASSWORD'] %>
tmc_data:
adapter: mysql2
encoding: utf8
database: tmc_data
username: <%= Rails.application.credentials.tmc_data_db[:username] %>
password: <%= Rails.application.credentials.tmc_data_db[:password] %>
host: tmc-data.cluster-ro-xyz.us-east-1.rds.amazonaws.com
port: 3306
Controller Action
def tmc_identifications
#tmcs = TmcIdentification.all.select(:direction, :miles, :road, :tmc)
end
View
<%= raw(#tmcs.to_json) %>
Everything works fine in development, but not in production. The same database and credentials are used in production for the "tmc_data" connection.
I assume I'm having some thread safety issues, but I'm not sure how to fix that.
The way I solved this problem is the following way:
Models:
class TmcData < ActiveRecord::Base
self.abstract_class = true
establish_connection(:tmc_data)
end
class TmcReading < ApplicationRecord
self.table_name = "TMC_Readings"
end
class TmcIdentification < ApplicationRecord
self.table_name = "TMC_Identification"
end
More details: https://www.thegreatcodeadventure.com/managing-multiple-databases-in-a-single-rails-application/
Also, I stopped connecting to the same secondary database with my development and production environment.

mysql Databases how can I fix this?

Hi Im trying to set up a database to store emails using ruby, sinatra, ActiveRecord, and mysql. Any suggestions on what im doing wrong? Im trying to output it to a seperate page that only i can see and then post it using a url on hostgator.
require 'sinatra'
require 'activerecord'
# require 'sinatra-activerecord'
get '/' do
erb :index
end
def save_email (email)
file.print(email)
end
get '/email' do
params[:email]
# # redirect '/'
end
post '/email' do
params[:email]
#email = params[:email]
erb :email, :locals => {:email => params[:email]}
end
# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'mysql', # or 'postgresql'
host: 'localhost',
database: 'Stored_Emails',
)
class Stored_Emails < Sinatra::Application
end
class Stored_Emails < ActiveRecord::Base
end
ActiveRecord::Migration.create_table :email do |t|
t.string :emails
end
create_table :emails, force: true do |t|
t.string :email
t.belongs_to :email, index: true
end
get '/email' do
params[:email].all
end
Typically you break out your code into multiple files (we use folders named config, helpers, libraries, views, routes, models, migrations) and require them at the top of your app. However, if you want to put it in the same file and just use that and a Gemfile and Gemfile.lock that'll work too. Here's how it might look:
# Require your gems
require 'sinatra'
require 'activerecord'
# Libraries
# Models
class Stored_Emails < ActiveRecord::Base
end
# Configuration
# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'mysql', # or 'postgresql'
host: 'localhost',
database: 'Stored_Emails'
)
ActiveRecord::Migration.create_table :email do |t|
t.string :emails
end
# Migrations
create_table :emails, force: true do |t|
t.string :email
end
# Helpers
def save_email (email)
file.print(email)
end
# Routes
get '/' do
# Load whatever you want to show in your index page into class variables
erb :index
end
get '/email' do
Stored_Emails.all.to_json
end
post '/email' do
#email = Stored_Emails.find_by(params[:email])
erb :email
end
Now you're going to have to do a good bit of work to get this running. Here's what I suggest you read:
1) Sinatra documentation - http://www.sinatrarb.com/intro.html
routes
running your sinatra app
views with ERB
2) Bundler documentation for gems - http://bundler.io/
3) ActiveRecord documentation - http://guides.rubyonrails.org/active_record_basics.html
Connecting to a database Creating your database with a migration -
this is a one time deal Querying the database
Good Luck!

Rails 4.1.1 Postgres app with Mysql Legacy database Import

I've been building a rails app using a postgres database but of course I also have been tasked with importing data from a legacy mysql database.
The way I've been handling this so far:
# config/database.yml
development:
adapter: postgresql
encoding: unicode
database: myapp_development
pool: 10
username: myuser
password:
legacy_development:
adapter: mysql2
encoding: utf8
reconnect: false
database: myapp_legacy
pool: 10
username: myuser
password:
socket: /tmp/mysql.sock
# app/models/legacy.rb
class Legacy < ActiveRecord::Base
self.abstract_class = true
establish_connection "legacy_#{Rails.env}".to_sym
def self.import
self.find_each do |object|
imported_model = object.class.model.new object.attribute_map
object.report_failures unless imported_model.save
end
end
def self.import_all
Rails.application.eager_load!
self.subclasses.each {|subclass| subclass.import }
end
end
# app/models/legacy/chapter.rb
# a bunch of different subclasses like this
class Legacy::Chapter < Legacy
self.table_name = 'chapters'
def self.model
'Chapter'.constantize
end
def attribute_map
{
id: id,
name: name,
body: chapterBody
}
end
end
Then I have a rake task that runs Legacy.import_all. A lot of this was stolen from this post.
There's a few things wrong with this:
The main problem is, when i run Legacy.import_all it makes it through about half of the tables then I get an error like:
NoMethodError: undefined method 'import' for Legacy::SomeSubclass(Table doesn't exist):Class
I think this is because we just have too many connections in the pool. It seems though like it is looking for the SomeSubClass table_name from within the postgres database, but it should be looking on the mysql database.
This is probably because of the methods like:
def self.model
'Chapter'.constantize
end
in the above subclass. I am doing it like that instead of:
def self.model
Chapter
end
because I have a normal model (non-legacy) in my app also called Chapter and I was running into scoping issues there as well.
Anyways this is a huge mess and any thoughts about where I should dig would be greatly appreciated.
Thanks
Can you try prefixing subclass.import with ::
def self.import_all
Rails.application.eager_load!
self.subclasses.each {|subclass| ::subclass.import }
end

How to make a model point to non-default schema

I've searched all over and I can't find anything related to this.
Basically I have the default schema set to abc
In abc I have some tables, etc ...............
I want to make a model that uses table mobile_activity_logs in schema def
The default rails model looks like this:
class MobileActivityLogs < ActiveRecord::Base
# attr_accessible :title, :body
end
but the query is on abc.mobile_activity_logs and not def.mobile_activity_logs
abc.mobile_activity_logs doesn't exist
In the database.yml file:
tester:
adapter: mysql2
database: def
host:
port:
username:
password:
enable_call: true
flags: CLIENT_MULTI_RESULTS
In the model:
class MobileActivityLogs < ActiveRecord::Base
establish_connection "tester"
self.table_name = "mobile_activity_logs"
end
This is a bit ugly though as it will make a second connection just to access a different schema :/

500 Error in production adapter rails when starting new user session

I have been having this issue ever since I deployed and i can't figure it out.
I'll give some information and let me know if you need anything else! Thanks!
I, [2013-09-08T12:44:31.935143 #19456] INFO -- : Started POST "/sessions" for {IP ADDRESS} at 2013-09-08 12:44:31 -0700
I, [2013-09-08T12:44:31.937969 #19456] INFO -- : Processing by SessionsController#create as HTML
I, [2013-09-08T12:44:31.938102 #19456] INFO -- : Parameters: {"utf8"=>"✓", "authenticity_token"=>"{AUTHENTICITY TOKEN}", "email"=>"mike#test.com", "password"=>"[FILTERED]", "commit"=>"Log In"}
I, [2013-09-08T12:44:31.941064 #19456] INFO -- : Completed 500 Internal Server Error in 3ms
F, [2013-09-08T12:44:31.943631 #19456] FATAL -- :
ActiveRecord::StatementInvalid (Could not find table 'users'):
app/controllers/sessions_controller.rb:6:in `create'
Obviously it's telling me that the "users" table doesn't exist, but that BS, because it does. Perhaps it can't find the table? Which i ALSO think is wierd, because I created the table using Rails migrations.
Here is my production Adapter just for reference:
production:
adapter: mysql
database: {DATABASENAME}
username: {USERNAME}
password: {PASSWORD}
host: localhost
port: 3306
Here is my seeds file:
User.create([{ email: 'mike#test2.com' }, { password_digest: 'password' }])
And my user model:
class User < ActiveRecord::Base
has_secure_password
validates_uniqueness_of :email
end
And my sessions controller (handles the login):
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to root_url, notice: "Logged in!"
else
flash.now.alert = "Email or password is invalid"
render "new"
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, notice: "Logged out!"
end
end
I created the user directly in the database, so the issue isn't that the user doesnt exist, the log file is saying the table 'users' doesnt exist, but that is false as well...i really don't know whats going on...
OH, BTW this all works in development. Login, user creation, everything. I was using sqlite3 for development and switched to mysql for production, just screwed everything up....
Any help is appreciated!
For future reference, this is the fix if anyone else is having an issue with their seeds not working:
This is what I was using:
User.create([{ email: 'mike#test2.com' }, { password_digest: 'password' }])
This is what it should be:
users =User.create!(:email 'mike#test2.com', :password 'password', :password_confirmation 'password')
users.save
Using
Create!
instead of just plain
Create
enables validation, and the seed will fail and explain the problem. In my case, it was that I was using password_digest, which is the column name, instead of password and password_confirmation.
Also, save the seed creation in a variable (users in my case), then save said variable by doing this:
users.save
Simple as that!
Hope this helps a fellow newbie in the future!