How to configure ActiveRecord database connection with mysql2 gem - ruby-on-rails

Hey everyone Having an issue using ActiveRecord with the 'mysql2' gem. I'm using rails 4.0.4 There are these lines in my config/application.rb
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
when i try to run 'rails g model user' i get
invoke active_record
/Users/edjasper/.rvm/gems/ruby-2.1.1/gems/railties4.0.4/lib/rails/application/configuration.rb:110:in `database_configuration': Could not load database configuration. No such file - /Users/edjasper/Desktop/associations_challenge_8/config/database.yml (RuntimeError
any advice?

yes, you don't have database.yml in config dir
smth like
development:
adapter: mysql2
encoding: utf8
database: my_db_name
username: root
password: my_password
host: 127.0.0.1
port: 3306
secure_auth: false
also you should already have database.yml.example in your config dir for sample
by the way error message already told you about it :)
No such file - /Users/edjasper/Desktop/associations_challenge_8/config/database.yml

Related

How to connect rails development.sqlite3 database for the single ruby file?

I have a main.rb for Telegram bot. For creating Admin panel of the bot I have used the Rails.
So now I want to connect from main.rb file to the database which I created using Rails.
How to do it?
You need to do something like this inside of main.rb...
#!/usr/bin/ruby
require 'active_record'
require 'sqlite3'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'DB_NAME',
username: 'DB_USER',
password: 'DB_PASS',
host: 'localhost'
)
# This will connect to the bots tables, probably not what you wanted.
class Bot < ActiveRecord::Base
end

How can I use the methods in ActiveRecord::ConnectionAdapters::SchemaStatements in isolation?

I am writing a script which I can write in postgresql but would like to write using ActiveRecord. Most of the methods that I would like to use are located in ActiveRecord::ConnectionAdapters::SchemaStatements. Because this is a module how can I use these methods in an ActiveRecord::Base.transaction block. I've already tried calling the methods directly like so:
ActiveRecord::ConnectionAdapters::SchemStatements.drop_table etc.
This doesn't seem to work. Is it even possible to use ActiveRecord like this?
You need to require active_record, establish a connection to the database and then you can use all the methods through the connection method:
# test.rb
require 'active_record'
require 'pg'
# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: 'localhost',
database: 'database',
username: 'username',
password: 'passwd'
)
puts ActiveRecord::Base.connection.table_exists?('users')
Test run (when the users table indeed exists in my database):
$ ruby test.rb
true
I recently had to do the exact same thing, and, yes, this is possible. I started with a regular Rails project (rails new app) and stripped it down to fit my needs.
My final project structure has only the following folders and files (everything else was deleted):
/app/models/*
/bin/bundle
/bin/rake
/bin/spring
/config/application.rb
/config/boot.rb
/config/database.yml
/config/environment.rb
/config/environments/*
/db/schema.rb
/config.ru
/Gemfile
/Gemfile.lock
/Rakefile
My Gemfile contains:
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '< 5.0.0'
# Use mysql as the database for Active Record
gem 'mysql2' # <-- change this to PostgreSQL
I also have a script app.rb, which I placed at the root of the project:
# ensure that all dependent gems are installed before running
require_relative 'config/boot'
# include dependent libraries
require 'active_record'
require 'active_model'
require 'mysql2' # <-- change this to PostgreSQL
require 'yaml'
# set up environment and connect to the database
environment = ENV['RAILS_ENV'] || 'development'
database = YAML.load_file('config/database.yml')
ActiveRecord::Base.establish_connection database[environment]
# set up logging so you can use $logger.debug or $logger.info anywhere in your code
$logger = Logger.new(File.new("log/#{environment}.log", 'w'))
$logger.level = environment == 'development' ? Logger::DEBUG : Logger::INFO
# include dependent classes in same directory
# this step is optional as the required files can be included as needed
Dir['app/models/*.rb'].each { |file| require_relative file }
Now, suppose you have a model called User defined in /app/models/user.rb as
class User < ActiveRecord::Base
end
You can then write statements like the one below in any file that is included from app.rb:
#execute code as a single transaction
ActiveRecord::Base.transaction do
user1 = User.create!(first_name: 'Richard', last_name: 'Rahl')
user2 = User.create!(first_name: 'Kahlan', last_name: 'Amnell')
end
You can even use statements like has_many, belongs_to, etc in your models without any problems.
Hopefully, this will be enough to get you started. Let me know if you need more details.

rake corrupts development database

When I run rake to run specific/all test(s), it corrupts development database.
I verified that db for each environment is different.
database.yml
postgre_common_config: &postgre_common_config
adapter: postgresql
encoding: unicode
pool: 5
username: postgres # if using default PostgreSQL user then the value should be: postgres
password: postgres
host: localhost
development:
database: mag_development
<<: *postgre_common_config
test:
database: mag_test
<<: *postgre_common_config
production:
database: mag_production
<<: *postgre_common_config
test_helper.rb
ENV['RAILS_ENV'] = 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
fixtures :all
end
This is really annoying as it takes lot of time to prepare data to test specific feature manually. Please help.

ActionView::Template::Error (db_name must be a string or symbol):

Ok so i have a new rails app that i have on ubuntu 11.10 on ec2 and it has mongoid as the db and i keep getting this error
ActionView::Template::Error (db_name must be a string or symbol):
Here is my config/mongoid.yml
development:
host: localhost
database: mm_development
test:
host: localhost
database: mm_test
# set these environment variables on your prod server
production:
host: <%= ENV['MONGOID_HOST'] %>
port: <%= ENV['MONGOID_PORT'] %>
username: <%= ENV['MONGOID_USERNAME'] %>
password: <%= ENV['MONGOID_PASSWORD'] %>
database: <%= ENV['MONGOID_DATABASE'] %>
# slaves:
# - host: slave1.local
# port: 27018
# - host: slave2.local
# port: 27019
and my database.yml is blank because i didnt know what if anything needs to go there. Here is my gemfile for mongoid
gem 'rails', '3.2.3'
gem 'jquery-rails'
gem 'haml'
gem 'unicorn'
gem 'mongoid'
First i want to know if anyone know what i need to do with database.yml and then how do i solve this issue....mongo is up and running but this error is confusing
If you want to run with blank config/database.yml or remove it, you must remove all references to Active Record. The following worked for me, check it for config/application.rb and what I had to do to get a fresh Rails project to pass an initial test with your supplied Gemfile and config/mongoid.yml. Note that you also should comment out "fixtures :all" in test/test_helper.rb. I recommend that you recreate your equivalent of the following as a clean base from which to start. Hope that this helps.
$ ruby -v
ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-darwin11.3.0]
$ rails _3.2.3_ new free-11137-db_name
$ cd free-11137-db_name
Gemfile as per user
$ bundle install
$ gem install unicorn
$ bundle install
Using mongo (1.6.2)
Using mongoid (2.4.8)
$ rails g mongoid:config
config/mongoid.yml as per user
config/database.yml blank as per user
config/application.rb
#require 'rails/all'
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
# require "sprockets/railtie" # Uncomment this line for Rails 3.1+
remove all references to Active Record as follows
config/application.rb
#config.active_record.whitelist_attributes = true
config/environments/development.rb
#config.active_record.mass_assignment_sanitizer = :strict
#config.active_record.auto_explain_threshold_in_seconds = 0.5
config/environments/test.rb
#config.active_record.mass_assignment_sanitizer = :strict
test/test_helper.rb
#fixtures :all
$ rails g model person
$ cat app/models/person.rb
class Person
include Mongoid::Document
end
$ rm test/fixtures/people.yml
$ bundle exec rake test # succeeds
$ rm config/database.yml
$ bundle exec rake test # succeeds

Rails with Mongo Mapper

This is turning out to be the worst day for learning rails. Already failed to connect and configure to sqlite3, mysql databases I turned to mongo mapper and facing the same issues. When I try to start the rails server I get the following:
/usr/local/lib/ruby/gems/1.8/gems/activesupport-3.0.7/lib/active_support/dependencies.rb:239:in `require': no such file to load -- mongo_mapper (LoadError)
I have already installed mongo_mapper gem but when I do 'which mongo_mapper' it does not return anything.
Here is my mongo_config.rb file placed inside the initializers folder:
require "rubygems"
require "mongo_mapper"
MongoMapper.database = "blog-#{Rails.env}"
UPDATE 1:
I changed to the following:
require "rubygems"
include MongoMapper
MongoMapper.database = "blog-#{Rails.env}"
And now I get the following error:
/Users/azamsharp/Projects/railsprojects/blog/config/initializers/mongo_config.rb:2: uninitialized constant MongoMapper (NameError)
You must use bundler with rails 3. don't try to not use it. add the following to your Gemfile
source 'http://gemcutter.org'
source 'http://rubygems.org'
gem "rails", "3.0.7"
gem 'bson', "1.1.1"
gem 'bson_ext', "1.1.1"
gem 'mongo_mapper'
then run
bundle install
then rails server will work
In order to get mongo_mapper working in Rails (tested under Rails 3.1, should work in Rails 3.0.x as well), you have to follow these steps:
In Gemfile, add the mongo_mapper and bson gem:
gem 'mongo_mapper'
gem 'bson_ext'
Run bundle install
In the config/ directory, create a mongo.yml file like this one:
# config/mongo.yml
defaults: &defaults
host: 127.0.0.1
port: 27017
development:
<<: *defaults
database: db_development
username: user
password: password
test:
<<: *defaults
database: db_test
# set these environment variables on your prod server
production:
<<: *defaults
database:
username:
password:
In the config/initializers directory, create a mongo.rb file like this:
# config/initializers/mongo.rb
#include MongoMapper
db_config = YAML::load(File.read(File.join(Rails.root, "/config/mongo.yml")))
#
if db_config[Rails.env] && db_config[Rails.env]['adapter'] == 'mongodb'
mongo = db_config[Rails.env]
MongoMapper.connection = Mongo::Connection.new(mongo['host'] || 'localhost',
mongo['port'] || 27017,
:logger => Rails.logger)
MongoMapper.database = mongo['database']
if mongo['username'] && mongo['password']
MongoMapper.database.authenticate(mongo['username'], mongo['password'])
end
end
# Used for image uploads
# CarrierWave.configure do |config|
# mongo = db_config[Rails.env]
# config.grid_fs_database = mongo['database']
# config.grid_fs_host = mongo['host'] || 'localhost'
# config.grid_fs_access_url = "gridfs"
# config.grid_fs_username = mongo['username']
# config.grid_fs_password = mongo['password']
# end
# It's also possible to define indexes in the the model itself; however,
# a few issues are being worked out still. This is a temporary solution.
# Comment.ensure_index([["story_id", 1], ["path", 1], ["points", -1]])
# MongoMapper.ensure_indexes!
# Handle passenger forking.
# if defined?(PhusionPassenger)
# PhusionPassenger.on_event(:starting_worker_process) do |forked|
# MongoMapper.database.connect_to_master if forked
# end
# end
if defined?(PhusionPassenger)
PhusionPassenger.on_event(:starting_worker_process) do |forked|
MongoMapper.connection.connect if forked
end
end
Start the mongod server before starting the rails server and enjoy!
Try removing the require lines and replace them with include MongoMapper

Resources