mysql Databases how can I fix this? - mysql

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!

Related

Why is this migration not migrating on mysql

I am integrating a CAS client using rack-cas gem on an application using mysql database, When i run,
rails generate cas_session_store_migration as specified on the readme, it generates a migration 20140428130031_create_rack_cas_sessions.rb which looks like this:
class CreateRackCasSessions < ActiveRecord::Migration
def self.up
create_table :sessions do |t|
t.string :session_id, :null => false
t.string :cas_ticket
t.text :data
t.timestamps
end
add_index :sessions, :session_id
add_index :sessions, :cas_ticket
add_index :sessions, :updated_at
end
def self.down
drop_table :sessions
end
end
when i run rake db:migrate or bundle exec rake db:migrate nothing happens. The migration fails to take place and there is no error message(s). The same migration on another service using sqlite database migrates successfully.

undefined local variable or method `acts_as_gmappable'

I created a Heroku app which utilizes the gmaps4fails gem for one of the application's features.
When I tried to seed the database, I get
rake aborted!
undefined local variable or method 'acts_as_gmappable' for #<Class:0x00000004b5b928>
Any ideas how to fix this?
Everything works fine when testing locally.
Edit: Here's my model code
class Hall < ActiveRecord::Base
has_many :hall_features
has_many :green_features, :through => :hall_features
has_many :settings, :through => :pinned_halls
belongs_to :operational_unit
acts_as_gmappable
...
Migration:
class CreateHalls < ActiveRecord::Migration
def up
create_table 'halls' do |t|
t.string 'name'
t.text 'background'
t.text 'energy_info'
t.float 'latitude'
t.float 'longitude'
t.boolean 'gmaps'
t.timestamps
end
end
def down
drop_table 'halls' # deletes the whole table and all its data!
end
end
Here's the error from my terminal: http://i48.tinypic.com/zvoggg.png
Ugh .. put the gem under :development in Gemfile only. Including it in :production solved everything.
I'll be crying myself to sleep tonight. Some tears of happiness too.

At what point does ActiveRecord actually connect to the database?

I have a ruby script that is using ActiveRecord (2.3.12) to access a MySQL database. The flow goes something like, "read database values from a config file", "connect to database", "Create table A if it doesn't exist", "download and parse a file", "save parsed records to A".
The code looks like the following:
ActiveRecord::Base.establish_connection(
:adapter => 'mysql',
:database => database_name,
:username => username,
:password => password,
:host => "localhost",
:port => 3306
)
...
ActiveRecord::Schema.define do
create_table a, :force => true do |t|
t.string :last_name, :limit => 60, :default => "", :null => false
t.string :first_name, :limit => 30, :default => "", :null => false
t.string :middle_initial, :limit => 2, :default => ""
t.string :dob, :limit => 12, :default => "", :null => false
end
end unless A.table_exists?
However, if I put incorrect DB credentials, or a non-existent database name into the establish_connection method, the script doesn't seem to give any errors or throw any exceptions until I actually try to perform some operation on the database (i.e., create table A). I tried a begin-rescue-end around establish_connection, but it never went into the rescue block.
Why does establish_connection seem to not really...well...establish the connection? And for the life of me, I can't figure out what it is even supposed to return. The docs HERE sure don't seem to be any help.
Or am I doing something wrong? Please help!
I usually use ActiveRecord::Base.connection.active? statement to check the whether the ActiveRecord is really connected to database.
def establish_database_connection
begin
ActiveRecord::Base.establish_connection config["database"]
ActiveRecord::Base.connection.active?
logger.info "Connected to Database"
rescue Exception => e
logger.error "Exception db connection : #{e.message} "
raise "Database connection failed"
end
end
Without ActiveRecord::Base.connection.active? statement the above code won't raise any error on invalid credentials.
RSK's solution will leave a connection checked out for the current thread. If you don't want that, try this (adapted from https://gist.github.com/limhoff-r7/71ee6b1568b604e131a8, which is for Postgres only):
ActiveRecord::Base.establish_connection
# Check if the spec passed to `ActiveRecord::Base.establish_connection` can connect to the database.
#
# #return [true] if an active connection can be made to the database using the current config.
# #return [false] if an active connection cannot be made to the database.
def connection_established?
begin
# use with_connection so the connection doesn't stay pinned to the thread.
ActiveRecord::Base.connection_pool.with_connection {
ActiveRecord::Base.connection.active?
}
rescue Exception
false
end
end
I agree with #Luke Imhoff: Connections that are manually checked out from ActiveRecord's connection-pool, have to manually be returned to the pool.
As a note, however, I suggest to use the connection that ActiveRecord yields to the block
ActiveRecord::Base.connection_pool.with_connection { |con| con.active? }
Referring to the documentation of :with_connection:
I'm not an expert, but I always assumed that establish_connection was more of a connection definition, whereas the actual connection is made when it is used, in this case, when the table_exists? runs

RoR MySQL boolean value

Im having an issue with MySql.Created a boolean column(Via a Database Migration) in MySql Database,toggled the value to "true".I Have a method in my rails App that checks if the value in that column is true,but it always returns false(even when called from a ruby console). Tried using the Same Migration on a SQLite Database and the same code returns true on the same Column. Observed MySQL uses tinyint for boolean values(1 == true) .
Please how can i correct this?
My Migration:
def self.up
create_table :users do |t|
t.string :name
t.string :email
t.boolean :admin , default => false
...
t.timestamps
end
end
...
Then i used the Faker Gem to Populate my Database, toggling one user in it setting it's value to true
Sample Data Via Faker Gem
admin = User.create!(:name => "sample",
:email => "sample#sample.com",
:password => "sample",
:password_confirmation => "sample")
admin.toggle!(:admin) #toggling value of admin to true just for this user

Using active record and mysql on ruby script

I've been trying to use mysql and active record on a ruby script but I'm getting the following message: Outdated mysql gem. Upgrade to 2.8.1 or later. In your Gemfile: gem 'mysql', '2.8.1'. Or use gem 'mysql2' (RuntimeError). Before I was getting a message about gem 'mysql2' missing but then i checked the source code on the connection adapters in active record and saw that it require mysql gem which i didnt have installed.
this is my script:
require 'rubygems'
require 'active_record'
require 'mechanize'
require 'nokogiri'
require 'active_record'
require 'mysql2'
gem 'mysql2'
ActiveRecord::Base.establish_connection ({
:adapter => "mysql",
:host => "localhost",
:username => "root",
:password => "",
:database => "rainalytics"})
ActiveRecord::Schema.define(:version => 20110320035328) do
create_table "score_logs", :force => true do |t|
t.integer "blog_posts"
t.integer "featured"
end
create_table "users", :force => true do |t|
t.datetime "created_at"
t.datetime "updated_at"
end
end
class User < ActiveRecord::Base
has_many :score_logs
end
class ScoreLog < ActiveRecord::Base
belongs_to :user
end
Im not using the 'require 'mysql2' or 'gem 'mysql2' parts, and it seems to be working fine, I also have additional {} inside the ActiveRecord::Base block
hope this can help someone in future :)
This is what I use
ruby 1.9.2p318 (2012-02-14 revision 34678) [x86_64-darwin11.2.0]
Rails 3.1.0
require "rubygems"
require "active_record"
ActiveRecord::Base.establish_connection ({
:adapter => "mysql2",
:host => "localhost",
:username => "root",
:password => "root",
:database => "cybercellar"})
class Zone < ActiveRecord::Base
end
zone = Zone.all
print zone
then I navigate to my app folder and run the file
ruby script/test.rb